PHP Foreach with Nested Array

PHP foreach with Nested Array?

If you know the number of levels in nested arrays you can simply do nested loops. Like so:

//  Scan through outer loop
foreach ($tmpArray as $innerArray) {
// Check type
if (is_array($innerArray)){
// Scan through inner loop
foreach ($innerArray as $value) {
echo $value;
}
}else{
// one, two, three
echo $innerArray;
}
}

if you do not know the depth of array you need to use recursion. See example below:

//  Multi-dementional Source Array
$tmpArray = array(
array("one", array(1, 2, 3)),
array("two", array(4, 5, 6)),
array("three", array(
7,
8,
array("four", 9, 10)
))
);

// Output array
displayArrayRecursively($tmpArray);

/**
* Recursive function to display members of array with indentation
*
* @param array $arr Array to process
* @param string $indent indentation string
*/
function displayArrayRecursively($arr, $indent='') {
if ($arr) {
foreach ($arr as $value) {
if (is_array($value)) {
//
displayArrayRecursively($value, $indent . '--');
} else {
// Output
echo "$indent $value \n";
}
}
}
}

The code below with display only nested array with values for your specific case (3rd level only)

$tmpArray = array(
array("one", array(1, 2, 3)),
array("two", array(4, 5, 6)),
array("three", array(7, 8, 9))
);

// Scan through outer loop
foreach ($tmpArray as $inner) {

// Check type
if (is_array($inner)) {
// Scan through inner loop
foreach ($inner[1] as $value) {
echo "$value \n";
}
}
}

Loop through nested arrays PHP

Sounds like you're trying to loop through the values of a "multidimensional array". You're starting correctly by going through your array with a loop, but then you're stuck because each element in your loop is... another array. So, to echo out the values of the child array, you want to run a second loop inside of your loop. Essentially, if your loop hits a child array, you want to loop through that array too. If you know your array is made of child arrays only, you can do this like so:

<?php
foreach ($events as $event) {

foreach($event as $ev) {

echo $ev;
}
}

If you need the keys, that adds a slight layer of complexity, but nothing you can't manage.

<?php
foreach ($events as $event) {
foreach ($event as $k=>$v) {
echo $k .': '. $v;
}
}

There are some examples in the php manual as well. You can also add in conditionals if you only need data from specific keys. Good luck!

PHP foreach loop in nested array

From what I see, this seems like a json and not an array. In that case, you should do this first:

$array =  json_decode($array, true);

When it comes to the array traversal, you can try something like this:

foreach($array['data']['results']['titles'] as $data) {
echo "Title:".$data['title'];
echo "<br/>";
echo "ID:".$data['id'];
echo "<br/>";
echo "URL:".$data['url'];
echo "<hr/>";
}

Hope this helps.

PHP foreach only returns first [0] of nested array

Your counter variable isn't doing anything as your foreach will only iterate over $inner[0] and then stop. You need to add a third level of iteration:

foreach($pixa_feedback as $inner){
// check type
if(is_array($inner)){
// iterate through nested array
foreach ($inner as $values){
foreach ($values as $key => $value) {
echo $key . ": " . $value . " <br>";
}
}
}
}

Output:

url: www.someurl.com <br>id: 11 <br>
url: www.differenturl.com <br>id: 22 <br>

Demo on 3v4l.org

PHP echo data from nested array (foreach loop)

First, array-keys must be in Quotation marks:

  • no: $order[items][0][item_title]

  • yes: $order['items'][0]['item_title']

Normally your PHP version throws a warning:

Warning: Use of undefined constant item_title - assumed 'item_title' (this will throw an Error in a future version of PHP)

You can iterate over the array:

foreach($order['items'] as $item) {
echo $item['item_title']."<br/>";
}

If you have a nested array (array of orders and each order has an array of items) you can nest the foreach.

$orders = readCSV('filename.csv');

foreach ($orders as $orderId=>$order) {
foreach($order['items'] as $item) {
if (!empty($item['item_title'])) echo $item['item_title']."<br/>";
}
}

. concat two strings. You don't Need two echo-commands.

Pay attention to the wording, that makes the code more readable.

foreach (<plural> as <singular>)

PHP foreach loop on unknown depth multidimensional array

Create a recursive function that checks if the element is an array, then if it is - call the function again, otherwise create the list-item as normal.

function my_print($array) {
$output = "<ul>";
foreach ($array as $value) {
if (is_array($value)) {
$output .= "<li>".my_print($value)."</li>";
} else {
$output .= "<li>".$value."</li>";
}
}
$output .= "</ul>";
return $output;
}

With an array as

$array = ['value', 'value',
['array 1', 'array 1',
['array 2']],
['array with more depth',
['array deep',
['array deeper']]]
];

..the output will be (although not formatted - formatted here for visual comparing with the array),

<ul>
<li>value</li>
<li>value</li>
<li>
<ul>
<li>array 1</li>
<li>array 1</li>
<li>
<ul>
<li>array 2</li>
</ul>
</li>
</ul>
</li>
<li>
<ul>
<li>array with more depth</li>
<li>
<ul>
<li>array deep</li>
<li>
<ul>
<li>array deeper</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
  • Live demo at https://3v4l.org/mTQHI

php - How to insert a foreach loop inside a multidimensional array

I want say thank you to @adrianRosi for the help and the input he gives me.

In the end I find my solution, that it's json_encode the array before add into $data in json format.

in this way:

            $product_list = [];    

foreach ($order->pad_products as $product) {
$product_list[] = array(
"id" => "$id",
"..." => "...",
);
};

$data_products['lines'] = $product_list;
$json_products = json_encode($data_products);
$json_products_edit = substr($json_products, 1, -1); // to delete the {}

$prezzo_totale = $order->pad_price_total;

$json_data = '{
...
...
'.$json_products_edit.'
}';

PHP: Foreach in a multidimensional array

change your loop as

foreach($carss as $key => $car){
echo $key ." ". $car['brand'] . "<br>";
}

foreach loop nested array json php

You have an object instead if array. You must work with data as an object...

foreach ($getexvolume->rows as $row) {
foreach ($row->components as $component) {
echo $component->converted_amount;
}
}

PHP How To Turn Nested Foreach Into An Array of Arrays (Multidimensional Array)

Here you go

$assignmentsYES = array ( 0 => '1001', 1 => '1002', 2 => '1004', 3 => '1005', 4 => '1007', 5 => '1008', 6 => '1009', 7 => '1015', 8 => '1028', 9 => '1029', );
$studentIDsubmissions = array ( 0 => '346623@guhsd.net|TD-Share Test #1001|NO', 1 => '346623@guhsd.net|TD-Share Test #1001|NO', 2 => '346623@guhsd.net|TD-Share Test #1001|NO', 3 => '346623@guhsd.net|TD-Share Test #1001|NO', 4 => '346623@guhsd.net|TD-No Excuse Reflection #1002|YES', 5 => '346623@guhsd.net|TD-No Excuse Reflection #1002|YES', 6 => '346623@guhsd.net|TD-No Excuse Reflection #1002|YES', 7 => '346623@guhsd.net|TD-About Me #1004|YES', 8 => '346623@guhsd.net|TD-Calendar #1007|YES', 9 => '346623@guhsd.net|TD-Wage Tracker #1008|YES', 10 => '346623@guhsd.net|TD-Stock Portfolio #1009|YES', 11 => '346623@guhsd.net|TD-Collaboration #1005|YES', 12 => '346623@guhsd.net|TD-Stock Portfolio #1009|YES', 13 => '346623@guhsd.net|TD-Collaboration #1005|YES', 14 => '346623@guhsd.net|TD-Dream Vacation Presentation #1015|YES', );

$combinedAssignmentData = [];
foreach($assignmentsYES as $key=>>$level){
$combinedAssignmentData[$level] =
array_filter(
$studentIDsubmissions,
function($item)use($level){
return strpos($item, '#'.$level) !== false;
}
);
}

print_r($combinedAssignmentData);

Output

Array
(
[1001] => Array
(
[0] => 346623@guhsd.net|TD-Share Test #1001|NO
[1] => 346623@guhsd.net|TD-Share Test #1001|NO
[2] => 346623@guhsd.net|TD-Share Test #1001|NO
[3] => 346623@guhsd.net|TD-Share Test #1001|NO
)

[1002] => Array
(
[4] => 346623@guhsd.net|TD-No Excuse Reflection #1002|YES
[5] => 346623@guhsd.net|TD-No Excuse Reflection #1002|YES
[6] => 346623@guhsd.net|TD-No Excuse Reflection #1002|YES
)

[1004] => Array
(
[7] => 346623@guhsd.net|TD-About Me #1004|YES
)

[1005] => Array
(
[11] => 346623@guhsd.net|TD-Collaboration #1005|YES
[13] => 346623@guhsd.net|TD-Collaboration #1005|YES
)

[1007] => Array
(
[8] => 346623@guhsd.net|TD-Calendar #1007|YES
)

[1008] => Array
(
[9] => 346623@guhsd.net|TD-Wage Tracker #1008|YES
)

[1009] => Array
(
[10] => 346623@guhsd.net|TD-Stock Portfolio #1009|YES
[12] => 346623@guhsd.net|TD-Stock Portfolio #1009|YES
)

[1015] => Array
(
[14] => 346623@guhsd.net|TD-Dream Vacation Presentation #1015|YES
)

[1028] => Array
(
)

[1029] => Array
(
)

)

Sandbox

*PS
I added a # in here strpos($item, '#'.$level), which will improve the accuracy a bit. It would be better to use a regular expression (in the array filter callback)

function($item)use($level){
return preg_match('/#'.$level.'\|/', $item); //match `#{id}|`
}

Consider for example matching 1001 to id 10012 ~ strpos will just match the 1001 part with no regard.

If the oddly numbered keys for the sub array bug you you can wrap the array_filter in array_values(array_filter(....)); to reset them. Array filter retains the keys from the original array. In most cases the keys don't really matter, so I wouldn't worry about it unless you really have to.

Update

After thinking about it and posting this

be better to use a regular expression

Why don't we go with this one:

$assignmentsYES = array ( 0 => '1001', 1 => '1002', 2 => '1004', 3 => '1005', 4 => '1007', 5 => '1008', 6 => '1009', 7 => '1015', 8 => '1028', 9 => '1029', );
$studentIDsubmissions = array ( 0 => '346623@guhsd.net|TD-Share Test #1001|NO', 1 => '346623@guhsd.net|TD-Share Test #1001|NO', 2 => '346623@guhsd.net|TD-Share Test #1001|NO', 3 => '346623@guhsd.net|TD-Share Test #1001|NO', 4 => '346623@guhsd.net|TD-No Excuse Reflection #1002|YES', 5 => '346623@guhsd.net|TD-No Excuse Reflection #1002|YES', 6 => '346623@guhsd.net|TD-No Excuse Reflection #1002|YES', 7 => '346623@guhsd.net|TD-About Me #1004|YES', 8 => '346623@guhsd.net|TD-Calendar #1007|YES', 9 => '346623@guhsd.net|TD-Wage Tracker #1008|YES', 10 => '346623@guhsd.net|TD-Stock Portfolio #1009|YES', 11 => '346623@guhsd.net|TD-Collaboration #1005|YES', 12 => '346623@guhsd.net|TD-Stock Portfolio #1009|YES', 13 => '346623@guhsd.net|TD-Collaboration #1005|YES', 14 => '346623@guhsd.net|TD-Dream Vacation Presentation #1015|YES', );

$combinedAssignmentData = [];
foreach($assignmentsYES as $key=>$level){
$combinedAssignmentData[$level] = preg_grep('/#'.$level.'\|/', $studentIDsubmissions);
}

print_r($combinedAssignmentData);

Using Preg Grep is a bit cleaner then array filter and a callback with a regular expression. I also realized you had a superficial loop in there $levels = array($assignedIDs); or basically $levels = array($level); or just $level.

Same output as before

Sandbox



Related Topics



Leave a reply



Submit