Iterate Multi-Dimensional Array with Nested Foreach Statement

Iterate Multi-Dimensional Array with Nested Foreach Statement

If you want to iterate over every item in the array as if it were a flattened array, you can just do:

foreach (int i in array) {
Console.Write(i);
}

which would print

123456

If you want to be able to know the x and y indexes as well, you'll need to do:

for (int x = 0; x < array.GetLength(0); x += 1) {
for (int y = 0; y < array.GetLength(1); y += 1) {
Console.Write(array[x, y]);
}
}

Alternatively you could use a jagged array instead (an array of arrays):

int[][] array = new int[2][] { new int[3] {1, 2, 3}, new int[3] {4, 5, 6} };
foreach (int[] subArray in array) {
foreach (int i in subArray) {
Console.Write(i);
}
}

or

int[][] array = new int[2][] { new int[3] {1, 2, 3}, new int[3] {4, 5, 6} };
for (int j = 0; j < array.Length; j += 1) {
for (int k = 0; k < array[j].Length; k += 1) {
Console.Write(array[j][k]);
}
}

PHP Nested foreach on multi dimensional array

$options = array(
'type' => array('Old', 'Latest', 'GOLD 1.0', 'GOLD 1.1', 'GOLD 1.2', 'GOLD 1.3'),
'purity' => array('GOLD', 'SILVER', 'BRONZE'),
'model' => array('Rough', 'Neat', 'mixed', 'Random'),
);

// Create an array to store the permutations.
$results = array();
foreach ($options as $values) {
// Loop over the available sets of options.
if (count($results) == 0) {
// If this is the first set, the values form our initial results.
$results = $values;
} else {
// Otherwise append each of the values onto each of our existing results.
$new_results = array();
foreach ($results as $result) {
foreach ($values as $value) {
$new_results[] = "$result $value";
}
}
$results = $new_results;
}
}

// Now output the results.
foreach ($results as $result) {
echo "$result<br />";
}

Nested 'foreach' for multidimensional array

$value is an array, echo will only print strings, you need to either JSON encode your $value and echo it or use var_dump. If your intended output was more complex than this then you would need to expand on your question.

Print Multi-dimensional array using loop in PHP

you have associative array inside associative array
You have to loop the first associative array
and inside it loop the associative array
like this

foreach($bazar as $key => $val){

echo $key.'<br>';

foreach($val as $k => $v){
echo $k . ' -> ' .$v . '<br>';
}

}

How to combine two multi-dimensional arrays based on key value pairs without nested foreach loop?

If you want to remove the nested loop to reduce time of execution, you can do it by two passes

// save items of noteArr for each processId
$temp = [];
foreach($noteArr as $k => $note) {
$temp[$note['processId']][] = $note;
}

// and add saved sub-arrays to the source one
$newArr = [];
$i = 0;
foreach($fileArr as $file){
$newArr[$i] = $file;
if(isset($temp[$file['processId']]))
$newArr[$i]['notes'] = $temp[$file['processId'];
$i++;
}

better way to write nested foreach loop, multiple array comparison php

The complexity of two-nested-foreach solution is O(n * k), where n = len(array1) and k = len(array2). However you can achieve a smaller complexity O(n + k) via using hash tables (assoc arrays in PHP world).

$twoByLinkedId = [];
foreach ($arrayTwo as $x) { // K iterations
if (empty($twoByLinkedId[$x['linkedId']])) {
$twoByLinkedId[$x['linkedId']] = [];
}
array_push($twoByLinkedId[$x['linkedId']], $x);
}

foreach ($arrayOne as $el) { // N iterations
$entries = empty($twoByLinkedId[$el['id']])
? []
: $twoByLinkedId[$el['id']];
foreach ($entries as $entry) { // only few iterations
/* output $entry */
}
}

So you can see that the complexity of the solution is O(k + n*t), where t is a a small number.

Of course, the trick makes sense only if the lengths of both arrays are really big, otherwise simple nested foreach is a good solution too.

PHP: Iterating Through a multidimensional Array (4D)

By using a series of nested foreach with key => value iterators you can get the output you want; the key is not to output the date parts until you get to the bottom of the loops:

foreach ($post_search as $year => $months) {
foreach ($months as $month => $days) {
foreach ($days as $day => $files) {
foreach ($files as $file) {
echo "File $file:\nYear: $year\nMonth: $month\nDay: $day\n";
}
}
}
}

Output (for your sample data):

File default.md:
Year: 2019
Month: 5
Day: 12
File default.md:
Year: 2019
Month: 12
Day: 22
File default.md:
Year: 2020
Month: 5
Day: 19

Demo on 3v4l.org



Related Topics



Leave a reply



Submit