Looping a Multidimensional Array in PHP

Looping a multidimensional array in php

You're best using the foreach construct to loop over your array. The following is untested and is off the top of my head (and probably therefore not as thought through as it should be!) but should give you a good start:

foreach ($mainArray as $event)
{
print $event["eventTitle"];

foreach ($event["artists"] as $artist)
{
print $artist["name"];
print $artist["description"];

$links = array();
foreach ($artist["links"] as $link)
{
$links[] = $link["URL"];
}
print implode(",", $links);
}
}

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 fill multidimensional array with loop

In case you can't initialize arrays (Like suggested in @Barmar Answer), you need to look for the array key to override it with an array. Like here :

$days=array('Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
);
print_r($days);

//Example
$res[0]['name']="Sunday";
$res[0]['ID']="7";
$res[1]['name']="Monday";
$res[1]['ID']="1";

foreach($res as $k => $v){
$daykey = array_search($res[$k]['name'], $days);
if ($daykey !== false) {
$days[$daykey]=array($res[$k]['name']=>array('ID'=>$res[$k]['ID'],'name'=>$res[$k]['name']));
} else {
//do nothing... or whatever
}
}
print_r($days);

How to Loop through multi dimensional array of $_FILES array

You can use this:

$keys = array_keys($_FILES); // get all the fields name
$res = array_map(null, ...array_values($_FILES)); // group the array by each file
$res = array_map(function ($e) use ($keys) {return array_combine($keys, $e);}, $res); // insert the field name to result array

Documentation:

array-keys, array-map and array-combine

Live example: 3v4l

Multidimensional array in PHP using foreach loop

Use the following, Tested and working

$filterArray = array();
$i = 0;
foreach($salary as $dept => $employee){
foreach($employee as $index => $data){
if($data['salary'] > 10000){
$filterArray[$i]['deprtment'] = $dept;
$filterArray[$i]['name'] = $data['name'];
$filterArray[$i]['salary'] = $data['salary'];
}
$i++;
}
}

Result :-

Array
(
[1] => Array
(
[deprtment] => PHP
[name] => Raj
[salary] => 15000
)

[2] => Array
(
[deprtment] => PHP
[name] => Mihir
[salary] => 12000
)

[3] => Array
(
[deprtment] => Flex
[name] => Vijay
[salary] => 14000
)

)

php: How to foreach a multidimensional array?

The array you're trying to iterate with your foreach loop is not the same as the array you have. In order to use that loop, your array would need to be like this instead:

[
[
'work_time' => 0.00,
'break_time' => 0.00,
'meeting_time' => 0.00,
'login_time' => '10:11',
'logout_time' => '00:00',
'work_date' => '2018-04-13'
],
[
'work_time' => 3.96,
'break_time' => 0.00,
'meeting_time' => 0.00,
'login_time' => '08:48',
'logout_time' => '13:00',
'work_date' => '2018-04-16'
],
[
'work_time' => 7.75,
'break_time' => 1.06,
'meeting_time' => 0.00,
'login_time' => '09:09',
'logout_time' => '17:59',
'work_date' => '2018-04-17'
],
];

The array you have looks like the type of input you get if you have an HTML form with multiple rows of inputs with names like this:

<input type="text" name="work[work_time][]">

If that is the case, you can get an array like the one I showed above instead by switching the keys around and specifying a numeric key for each row:

<input type="text" name="work[0][work_time]">

Then it will make more sense to access the data as rows. If that's not the case, well, never mind. :)


On the other hand, with the array you have, you can just iterate one of the inner arrays directly. For example, if you wanted to show login_time values, it's just

foreach ($Work['login_time'] as $login_time) {
echo $login_time;
}

If you need to get corresponding values from the other inner arrays, you can use the key from the array you're iterating to access those as well:

foreach ($Work['login_time'] as $key => $login_time) {
echo 'login time: ' . $login_time . ', work_date: ' . $Work['work_date'][$key];
}

how to create multidimensional array using a foreach loop in php?

My guess is your foreach loop looks like this:

$result = array();
foreach($members as $member) {
$result['firstname'][] = $member['firstname'];
$result['last_name'][] = $member['last_name'];
//etc
}

And it should be something like this:

$result = array();
foreach($members as $member) {
$result[] = array(
'firstname' => $member['firstname'],
'last_name' => $member['last_name'],
'job' => $member['job'],
'desc' => $member['desc'],
'image_url' => $member['image_url']
);
}

Update based on sample code:

The POST fields are arrays, so you have to make sure all fields are posted for every member, as the for loop is based on all fields having the same amount of values.

$fname = $_POST['first_name'];
$lname = $_POST['last_name'];
$job = $_POST['job'];
$desc = $_POST['desc'];
$photo = $_POST['image_url'];

$memberdata = array();

// we iterate the firstname field and access the same indexes from the other fields. The $i starts with 0 and gets incremented until it iterated over all the firstnames
for($i = 0; $i < count($fname); $i++) {
$memberdata[] = array(
'first_name' => $fname[$i], // we access the firstname at the current index
'last_name' => $lname[$i],
'job' => $job[$i],
'desc' => $desc[$i],
'image_url' => $photo[$i]
);
}

var_dump($memberdata);

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

Loop through a two-dimensional array

In order to echo out the bits you have to select their index in each array -

foreach($array as $arr){
echo '<a href="'.$arr[0].'">'.$arr[1].'</a>';
}

Here is an example.

PHP- Loop through multidimensional array and reduce arrays if key found

Try

$result = array_reduce($products, function ($result, $product) {
foreach ($result as $index => $value) {
if ($value['product_id'] == $product['product_id']) {
$result[$index]['total_price'] += $product['total_price'];

return $result;
}
}
$result[] = $product;
return $result;
}, []);

But I strongly recomment use BCMath functions instead of working with floats.

So its better to write

$result[$index]['total_price'] = bcadd($result[$index]['total_price'], $product['total_price'], 2);

instead of

$result[$index]['total_price'] += $product['total_price'];

Update

We can rewrite above version to nested foreach like so:

$reducer = function ($result, $product) {
foreach ($result as $index => $value) {
if ($value['product_id'] == $product['product_id']) {
$result[$index]['total_price'] += $product['total_price'];

return $result;
}
}
$result[] = $product;
return $result;
};

$result = [];

foreach($products as $product) {
$result = $reducer($result, $product);
}

so we can see it is just foreach loop which calls function which contains another foreach.
We need another foreach because we need the way to determine if array contains product_id.
We can index result with product_id so we can avoid secind foreach:

$result = array_reduce($products, function ($result, $product) {
$productId = $product['product_id'];
if(isset($result[$productId])) {
$result[$productId]['total_price'] += $product['total_price'];
return $result;
}
$result[$productId] = $product;
return $result;
}, []);

and then if you need indexes to be ordered from zero just call array_values($result)



Related Topics



Leave a reply



Submit