I am trying to search for a value exist in multidimensional array, if exist add a new key/value pair. But i am not able to insert the new key/value pair. the multidimensional array $data is shown below.
Array ( [0] => Array ( [num] => +12000000000 [state] => eeee )
[1] => Array ( [num] => +12000000001 [state] => ) )
Another normal array $i is
Array ( [Sss] => +12000000000 [MS] => +12000000001 [KNum] => +919000000000 )
Search for num from $i exist in $data array using the below.
foreach($i as $key => $value){
$s[]= searchForId($value, $data,$key); //Edited
}
function searchForId($id, $array, $k) {
foreach ($array as $key => $val) {
if ($val['num'] === $id) {
//return $key;
echo "<br>------" . $key;
echo "<br>------" . $k;
echo "<br>------" . $id;
$array[$key]=$k;
$array[$key]['name']=$k;
return $array; //Edited
}
}
return null;
}
I tried with both the options which mentioned below but not inserting values into the $data multidimensional array. what is wrong here?
$array[$key]=$k;
$array[$key]['name']=$k;
PHP function trans parameter by value, not by reference(depreciated), if you want to modify the paremeter, return it.
Related
I have a two array first is:
$array1 = ['settings:rules:key','settings:scrum:way:other'];
I have explode $array1:
$temp_array = explode(":",$array1);
Now I have another array:
$array2 = [settings] => Array
( [rules] => Array
(
[0] => Array
(
[key] =>
[showValueField] => 1
)
)
something like this.
I need to access second array with key given in first array like:
$array2['settings']['rules']['key']
I have to get this keys from first array after explode
You can do it with this kind of loop:
function getVal($path, $arr) {
$current = $arr[array_shift($path)];
while (count($path)) {
$key = array_shift($path);
if (!is_array($current) || !isset($current[$key]))
return false; // protect against non-existing keys
$current = $current[$key];
}
return $current;
}
//example used:
$arr = array("settings" => array("rules" => array("key" => "AAA")));
echo getVal(explode(":",'settings:rules:key'), $arr) . PHP_EOL;
For the building of a url query I need to combine one value(key) of an array to all the values(value) of another array. Each combined key => value needs to be added to an array.
The problem here is that I can combine the values of the two arrays in two foreach statements, but it creates for every instance a new array.
Update
Having duplicates is impossible so mine initial output is correct.
$array1 array(
[0] => music
[1] => product
)
$array2 array(
[0] => '));waitfor delay '0:0:TIME'--1
[1] => '[TAB]or[TAB]sleep(TIME)='
)
public static function create_combined_array($array1, $array2)
{
$newArray = array();
foreach ($array1 as $key){
//key = [music]
foreach ($array2 as $value) {
//one of the values is = '));waitfor delay '0:0:__TIME__'--1
array_push($newArray, [$key => $value]);
}
}
return $newArray;
}
Implementation
$query_array = Utils::create_combined_array($params, $payload_lines);
print_r($query_array);
$query = http_build_query($query_array);
$this->url = $baseUrl . '?' . $query;
Build query output
protocol://localhost:8000?music='));waitfor delay '0:0:TIME'--1
Sample output
[54] => Array
(
[music] => ));waitfor delay '0:0:__TIME__'--[LF]1
)
[55] => Array
(
[music] => '));waitfor delay '0:0:__TIME__'--1
)
[56] => Array
(
[music] => '));waitfor delay '0:0:__TIME__'--[LF]1
)
[57] => Array
(
[music] => "));waitfor delay '0:0:__TIME__'--1
)
What I wanted to achieve is impossible in PHP.
Example duplicates
Array(
[music] => "));waitfor delay '0:0:__TIME__'--1
[music] => '/**/or/**/benchmark(10000000,MD5(1))#1
)
Use code below:
public static function create_combined_array($array1, $array2)
{
$newArray = array();
foreach ($array1 as $key){
foreach ($array2 as $i => $value) {
$newArray[$i][$key] = $value;
}
}
return $newArray;
}
The key line is $newArray[$i][$key] = $value;. It appends an array to the $newArray at $i index which is the index of your second array $array2.
I'm having trouble correctly iterating a multi-dimension array I am trying to retrieve the values for each well..value.
My Issue is I seem to have an array within an array which has an array for each key/pair value, I'm unsure how to loop through these and add the values to the database for each array.
Eg, if I have one form on my page the array return is below and further below that is what is returned with two forms etc
Array
(
[0] => Array
(
[0] => Array
(
[name] => sl_propid
[value] => 21
)
[1] => Array
(
[name] => sl_date
[value] => 04/01/2014
)
[2] => Array
(
[name] => sl_ref
[value] => Form1
)
[3] => Array
(
[name] => sl_nom_id
[value] => 12
)
[4] => Array
(
[name] => sl_desc
[value] => Form1
)
[5] => Array
(
[name] => sl_vat
[value] => 60
)
[6] => Array
(
[name] => sl_net
[value] => 999
)
)
)
My question is how do I iterate through the returned array no matter it's size and pull back each value?
I have tried nesting foreach loops, which did give me results, but only for one key/value pair which leads me to believe I'm doing the looping wrong, I can retrieve the values if I statically access them, which is of course no use normally.
foreach ($result as $array) {
print_r($array);
}
the above foreach returns the above arrays, adding another foreach removes the out "container" array but adding another foreach loop, returns only one key/value pair, which sort makes sense because the first index is an array, too, hope I haven't confused everyone else as much as already have myself D:.
Thank you for reading
Any help appreciated.
EDIT Using the below array walk recursive I get the output
$result = $this->input->post();
function test_print($item, $key)
{
echo "$key holds $item\n";
//$this->SalesLedgerModel->addInvoiceToLedger($key, $key, $key, $key, $key, $key, $key);
}
array_walk_recursive($result, 'test_print');
}
Which is almost what I want but how do I take each individual value and add it to my ModelFunction (to actually input the data to DB)
The function takes 7 parameters but I am unsure how to make sure the right info goes to the correct parameter
$this->SalesLedgerModel->addInvoiceToLedger($propid, $date, $ref, $nomid, $desc, $vat, $net);
My Controller function
function addInvoiceToLedger(){
$this->load->model('SalesLedgerModel');
// $propid = $this->input->post('propid');
// $date = $this->input->post('date');
// $ref = $this->input->post('ref');
// $nomid = $this->input->post('id');
// $desc = $this->input->post('desc');
// $vat = $this->input->post('vat');
// $net = $this->input->post('sl_net');
$results = $this->input->post();
//var_dump($results);
$size1 = sizeof($results)-1;
for($i=0; $i<=$size1; $i++)
{
$size2 = sizeof($results[$i])-1;
for($j=0; $j<=$size2; $j++)
{
$name = $results[$i][$j]['name'];
$value = $results[$i][$j]['value'];
echo $value . "\n" ;
$this->SalesLedgerModel->addInvoiceToLedger($value, $value, $value, $value, $value, $value, $value);
}
}
My Model function
function addInvoiceToLedger($propid, $date, $ref, $nomid, $desc, $vat, $net){
$data = array('sl_prop_id' => $propid, 'sl_date' => $date,
'sl_ref' => $ref, 'sl_nominal_sub' => $nomid, 'sl_invoice_desc' => $desc, 'sl_vat' => $vat, 'sl_amount' => $net);
$this->db->insert('salesledger', $data);
}
You can either write some recursive code to step through the array and call itself again if an element turns into an array, or write a very simple function and call it via array walk recursive which will then let you do whatever you like with the value:
<?php
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');
function test_print($item, $key)
{
echo "$key holds $item\n";
}
array_walk_recursive($fruits, 'test_print');
?>
Output:
a holds apple
b holds banana
sour holds lemon
Try this. It'll be much faster. Since 3 foreach loops is much costlier than 2 for loops (for loops are faster than foreach loops) -
$size1 = sizeof($results)-1;
if($size1 > 0)
{
for($i=0; $i<=$size1; $i++)
{
$size2 = sizeof($results[$i])-1;
if($size2 > 0)
{
for($j=0; $j<=$size2; $j++)
{
$name = $results[$i][$j]['name'];
$value = $results[$i][$j]['value'];
$insert = $this->your_model->insert($name, $value);
}
}
}
}
foreach ($result as $array) {
foreach($array as $arr){
foreach($arr as $a){
echo $a[value];
}
}
}
I have two multidimensional arrays. First one $properties contains english names and their values. My second array contains the translations. An example
$properties[] = array(array("Floor"=>"5qm"));
$properties[] = array(array("Height"=>"10m"));
$translations[] = array(array("Floor"=>"Boden"));
$translations[] = array(array("Height"=>"Höhe"));
(They are multidimensional because the contains more elements, but they shouldn't matter now)
Now I want to translate this Array, so that I its at the end like this:
$properties[] = array(array("Boden"=>"5qm"));
$properties[] = array(array("Höhe"=>"10m"));
I have managed to build the foreach construct to loop through these arrays, but at the end it is not translated, the problem is, how I tell the array to replace the key with the value.
What I have done is this:
//Translate Array
foreach ($properties as $PropertyArray) {
//need second foreach because multidimensional array
foreach ($PropertyArray as $P_KiviPropertyNameKey => $P_PropertyValue) {
foreach ($translations as $TranslationArray) {
//same as above
foreach ($TranslationArray as $T_KiviTranslationPropertyKey => $T_KiviTranslationValue) {
if ($P_KiviPropertyNameKey == $T_KiviTranslationPropertyKey) {
//Name found, save new array key
$P_KiviPropertyNameKey = $T_KiviTranslationValue;
}
}
}
}
}
The problem is with the line where to save the new key:
$P_KiviPropertyNameKey = $T_KiviTranslationValue;
I know this part is executed correctly and contains the correct variables, but I believe this is the false way to assing the new key.
This is the way it should be done:
$properties[$oldkey] = $translations[$newkey];
So I tried this one:
$PropertyArray[$P_KiviPropertyNameKey] = $TranslationArray[$T_KiviTranslationPropertyKey];
As far as I understood, the above line should change the P_KiviPropertyNameKey of the PropertyArray into the value of Translation Array but I do not receive any error nor is the name translated. How should this be done correctly?
Thank you for any help!
Additional info
This is a live example of the properties array
Array
(
[0] => Array
(
[country_id] => 4402
)
[1] => Array
(
[iv_person_phone] => 03-11
)
[2] => Array
(
[companyperson_lastname] => Kallio
)
[3] => Array
(
[rc_lot_area_m2] => 2412.7
)
[56] => Array
(
[floors] => 3
)
[57] => Array
(
[total_area_m2] => 97.0
)
[58] => Array
(
[igglo_silentsale_realty_flag] => false
)
[59] => Array
(
[possession_partition_flag] => false
)
[60] => Array
(
[charges_parkingspace] => 10
)
[61] => Array
(
[0] => Array
(
[image_realtyimagetype_id] => yleiskuva
)
[1] => Array
(
[image_itemimagetype_name] => kivirealty-original
)
[2] => Array
(
[image_desc] => makuuhuone
)
)
)
And this is a live example of the translations array
Array
(
[0] => Array
(
[addr_region_area_id] => Maakunta
[group] => Kohde
)
[1] => Array
(
[addr_town_area] => Kunta
[group] => Kohde
)
[2] => Array
(
[arable_no_flag] => Ei peltoa
[group] => Kohde
)
[3] => Array
(
[arableland] => Pellon kuvaus
[group] => Kohde
)
)
I can build the translations array in another way. I did this like this, because in the second step I have to check, which group the keys belong to...
Try this :
$properties = array();
$translations = array();
$properties[] = array("Floor"=>"5qm");
$properties[] = array("Height"=>"10m");
$translations[] = array("Floor"=>"Boden");
$translations[] = array("Height"=>"Höhe");
$temp = call_user_func_array('array_merge_recursive', $translations);
$result = array();
foreach($properties as $key=>$val){
foreach($val as $k=>$v){
$result[$key][$temp[$k]] = $v;
}
}
echo "<pre>";
print_r($result);
output:
Array
(
[0] => Array
(
[Boden] => 5qm
)
[1] => Array
(
[Höhe] => 10m
)
)
Please note : I changed the array to $properties[] = array("Floor"=>"5qm");, Removed a level of array, I guess this is how you need to structure your array.
According to the structure of $properties and $translations, you somehow know how these are connected. It's a bit vague how the indices of the array match eachother, meaning the values in $properties at index 0 is the equivalent for the translation in $translations at index 0.
I'm just wondering why the $translations array need to have the same structure (in nesting) as the $properties array. To my opinion the word Height can only mean Höhe in German. Representing it as an array would suggest there are multiple translations possible.
So if you could narrow down the $translations array to an one dimensional array as in:
$translation = array(
"Height"=>"Höhe",
"Floor"=>"Boden"
);
A possible loop would be
$result = array();
foreach($properties as $i => $array2) {
foreach($array2 as $i2 => $array3) {
foreach($array3 as $key => $value) {
$translatedKey = array_key_exists($key, $translations) ?
$translations[$key]:
$key;
$result[$i][$i2][$translatedKey] = $value;
}
}
}
(I see every body posting 2 loops, it's an array,array,array structure, not array,array ..)
If you cannot narrow down the translation array to a one dimensional array, then I'm just wondering if each index in the $properties array matches the same index in the $translations array, if so it's the same trick by adding the indices (location):
$translatedKey = $translations[$i][$i2][$key];
I've used array_key_exists because I'm not sure a translation key is always present. You have to create the logic for each case scenario yourself on what to check or not.
This is a fully recursive way to do it.
/* input */
$properties[] = array(array("Floor"=>"5qm", array("Test"=>"123")));
$properties[] = array(array("Height"=>"10m"));
$translations[] = array(array("Floor"=>"Boden", array("Test"=>"Foo")));
$translations[] = array(array("Height"=>"Höhe"));
function array_flip_recursive($arr) {
foreach ($arr as $key => $val) {
if (is_array($val)) {
$arr[$key] = array_flip_recursive($val);
}
else {
$arr = #array_flip($arr);
}
}
return $arr;
}
function array_merge_it($arr) {
foreach ($arr as $key => $val) {
if (is_array($val)) {
$arr[$key] = array_merge_it($val);
} else {
if(isset($arr[$key]) && !empty($arr[$key])) {
#$arr[$key] = $arr[$val];
}
}
}
return $arr;
}
function array_delete_empty($arr) {
foreach ($arr as $key => $val) {
if (is_array($val)) {
$arr[$key] = array_delete_empty($val);
}
else {
if(empty($arr[$key])) {
unset($arr[$key]);
}
}
}
return $arr;
}
$arr = array_replace_recursive($properties, $translations);
$arr = array_flip_recursive($arr);
$arr = array_replace_recursive($arr, $properties);
$arr = array_merge_it($arr);
$arr = array_delete_empty($arr);
print_r($arr);
http://sandbox.onlinephpfunctions.com/code/d2f92605b609b9739964ece9a4d8f389be4a7b81
You have to do the for loop in this way. If i understood you right (i.e) in associative array first key is same (some index).
foreach($properties as $key => $values) {
foreach($values as $key1 => $value1) {
$propertyResult[] = array($translations[$key][$key1][$value1] => $properties[$key][$key1][$value1]);
}
}
print_r($propertyResult);
I've a nested array whose print_r looks like this-
Array
(
[keyId] => Array
(
[hostname] => 192.168.1.127
[results] => Array
(
[1] => false
[2] => false
[3] => false
)
[sessionIDs] => Array
(
[0] => ed9f79e4-2640-4089-ba0e-79bec15cb25b
)
)
I would like to process(print key and value) of the "results" array. How do I do this?
I am trying to use array_keys function to first get all the keys and if key name is "results", process the array. But problem is array_keys is not reaching into the "results"
php's foreach loop is what you need.
foreach($arr['keyId']['results'] as $key => $value) {
//$key contains key and $value contains values.
}
The array you want is $array['keyID']['results']. From there you access the values with $array['keyID']['results'][1], $array['keyID']['results'][2], $array['keyID']['results'][3]
To loop through it just do this:
foreach($array['keyId']['results'] as $key => $value) {
echo $key . ' ' . $value;
}
or
for ($i = 1; $i <= 3; i++)
{
echo $i . ' ' . $array['keyID']['results'][i];
}
foreach($array['keyId']['results'] as $k => $v) {
// use $k and $v
}
One way to navigate through the array is this.
//Assuming, your main array is $array
foreach($array as $value) { //iterate over each item
if(isset($value['results']) && count($value['results'])) {
// ^ check if results is present
//Now that we know results exists, lets use foreach loop again to get the values
foreach($value['result'] as $k => $v) {
//The boolean values are now accessible with $v
}
}
}