Problem Iterating through a multi-dimensional array in PHP - php

Working on a Laravel application whereby I am consuming some data from an API. I get the response as a JSON object and convert to array. It appears as a complex multi-dimensional array
(nested arrays). Am trying to loop through it using a nested foreach so as to reach out to the id of each item but I keep failing..
The response is stored in a variable called usmDet
The array response
array:1 [▼
0 => array:1 [▼
0 => array:3 [▼
"id" => "74696"
"agents" => array:13 [▶]
"policies" => array:481 [▶]
]
1 => array:3 [▼
"id" => "1525"
"agents" => array:8 [▶]
"policies" => array:357 [▶]
]
]
1 => array:1 [▼
0 => array:3 [▼
"id" => "73401"
"agents" => array:1 [ …1]
"policies" => array:8 [ …8]
]
1 => array:3 [▼
"id" => "210"
"agents" => array:13 [ …13]
"policies" => array:773 [ …773]
]
]
]
My nested foreach
foreach($usmDet as $key => $value){
if(is_array($value)){
foreach($value as $key => $value){
echo $key." ".$value."<br>";
}
}
echo "<br>";
}

The id is part of the array, as you can access it like $value['id']
In the second foreach to prevent confusion you should select a different name for the key and the value.
Try it like this:
foreach($usmDet as $key => $value){
if(is_array($value)){
foreach($value as $k => $v){
echo $v['id'] . "<br>";
}
}
}
Result:
74696
1525
73401
210
Php demo
To get all the values for key "id" when multiple nested arrays, you could use array_walk_recursive
$ids = [];
array_walk_recursive($usmDet, function($value, $key) use (&$ids){
if ($key === "id") {
$ids[] = $value;
}
});
print_r($ids);
Php demo

Related

Array of Arrays returning non-sense when running in foreach

My project has an array made of a request with an array of inputs inside, as it follows:
array:8 [▼
"type_id" => array:1 [▼
0 => "1"
]
"zip_code" => array:1 [▼
0 => "88801500"
]
"street_address" => array:1 [▼
0 => "Avenida Getúlio Vargas"
]
"number" => array:1 [▼
0 => "asdasd"
]
"street_address_2" => array:1 [▼
0 => "asdasd"
]
"city_id" => array:1 [▼
0 => "4384"
]
"neighborhood" => array:1 [▼
0 => "Centro"
]
"created_by" => 2
]
But when I try to run said array on a foreach to insert it on the database, I get a result that doesnt make sense:
array:1 [▼
0 => "1"
]
My code:
dd($dataEnderecos); //This is for debug purposes, it shows the initial array on this question.
foreach ($dataEnderecos as $enderecos) {
dd($enderecos); //This is for debug purposes, it shows the secondary array on this question.
$enderecoID = $this->address->create($enderecos)->id;
$this->repository->enderecos()->attach($enderecoID);
}
I managed to fix this by using a for loop and using another variable to receive the results of the initial array:
for ($i = 0; $i < $limit; $i++) {
$insert = array(
'type_id' => $dataEnderecos['type_id'][$i],
// ^^^^ ^^^^ ^^^^
// Initial Array Secondary Array Index
);
}

How can I merge array recursively with a unique key?

I create my arrays like this:
foreach ($array as $key => $value) {
$array1[$value->getUuid()][$value->getFields()->getName()] = $value->getContent();
}
The result is array1:
array:2 [▼
"d8ab80f4f6" => array:16 [▶]
9087785727 => array:16 [▶]
]
I create another array in a little bit different way, array2:
array:2 [▼
"d8ab80f4f6" => array:3 [▶]
9087785727 => array:3 [▶]
]
Now I want to merge those arrays:
$output = array_merge_recursive($array1,$array2);
The output is:
array:3 [▼
"d8ab80f4f6" => array:19 [▶]
0 => array:3 [▶]
1 => array:16 [▶]
]
But I expect the output to be:
array:3 [▼
"d8ab80f4f6" => array:19 [▶]
"9087785727" => array:19 [▶]
]
array_merge and array_merge_recursive treat string keys differently from numeric keys:
If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively, so that if one of the values is an array itself, the function will merge it with a corresponding entry in another array too. If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended.
That's what's happening here. The key 9087785727 is numeric, so those entries are not being merged.
So you need to write your own loop.
$output = [];
foreach ($array1 as $key => $value) {
$output[$key] = array_merge($value, $array2[$key]);
}
DEMO
You can use next foreach loop with reference &:
foreach($ar1 as $key=>&$subar){
$subar = array_merge($subar,$ar2[$key]);
}
Demo

How can I prevent a loop to create keys without quotes?

This is my loop:
foreach ($array as $key => $value) {
$array1[$value->getUuid()][$value->getFields()->getName()] = $value->getContent();
}
The result is:
array:2 [▼
"d8ab80f4f6" => array:16 [▶]
9087785727 => array:16 [▶]
]
I do not understand, why the last key does not have quotes. How can I prevent this?

Unable to add 2 associative arrays

I am trying to add 2 associative arrays, but the new array only comes with an index for the second array.
This is what I am doing
$array = ['name' => 'address', 'value' => 'us'];
$arr = ['name' => 'joe', 'value' => 'doe'];
$arr[] = $array;
This is the result
array:3 [▼
"name" => "joe"
"value" => "doe"
0 => array:2 [▶]
]
I am expecting something like this
array:2 [▼
0 => array:2 [▶]
1 => array:2 [▶]
]
As you can see, there is no index for the first array, thus making the count 3 instead of 2. Please how do I fix this?
Just create another array and add the 2 arrays to it:
$newAr = [];
$newAr[] = $array;
$newAr[] = $arr;
var_dump($newAr);

how to get data to save from arrays inside array

i have form to make a bill for multiple products,
that form return request like this
#parameters: array:5 [▼
"quantity" => array:2 [▼
0 => "1"
1 => "2"
]
"product" => array:2 [▼
0 => "Mr. Jasen Beer,OliveDrab,XS"
1 => "Carlotta Yundt"
]
"date" => array:2 [▼
0 => "2019-12-29"
1 => "2019-12-29"
]
"id" => array:2 [▼
0 => "15"
1 => "11"
]
]
}
i need to loop all arrays to make insert all at once
thanks.
Try to loop it like this, you will get the array wrap every product's attributes:
$inserted_array = [];
foreach($parameters as $key => $values) {
foreach($values as $index => $val) {
$inserted_array[$index][$key] = $val;
}
}
\DB::table('table_name')->insert($inserted_array);
And I found that there is id in your array, remember to make it fillable.

Categories