PHP Foreach Loop Through Multidimensional Array

PHP foreach loop through multidimensional array

$last = count($arr_nav) - 1;

foreach ($arr_nav as $i => $row)
{
$isFirst = ($i == 0);
$isLast = ($i == $last);

echo ... $row['name'] ... $row['url'] ...;
}

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];
}

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

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 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.'
}';

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.

how to do a foreach loop values in a multidimensional array PHP

I would approach it like this:

$api = array (
'tracks' =>
array (
0 =>
array (
'album' =>
array (
'album_type' => 'album',
'artists' =>
array (
0 =>
array (
'external_urls' =>
array (
'spotify' => 'https://open.spotify.com/artist/4ovtyvs7j1jSmwhkBGHqSr',
),
'href' => 'https://api.spotify.com/v1/artists/4ovtyvs7j1jSmwhkBGHqSr',
'id' => '4ovtyvs7j1jSmwhkBGHqSr',
'name' => 'Olamide',
'type' => 'artist',
'uri' => 'spotify:artist:4ovtyvs7j1jSmwhkBGHqSr',
),
),
'external_urls' =>
array (
'spotify' => 'https://open.spotify.com/album/6fG2eFCgUmytQWL6umtsCh',
),
'href' => 'https://api.spotify.com/v1/albums/6fG2eFCgUmytQWL6umtsCh',
'id' => '6fG2eFCgUmytQWL6umtsCh',
'images' =>
array (
0 =>
array (
'height' => '640',
'url' => 'https://i.scdn.co/image/ab67616d0000b27387d20b9a27d5e14d74b5cb77',
'width' => '640',
),
1 =>
array (
'height' => '300',
'url' => 'https://i.scdn.co/image/ab67616d00001e0287d20b9a27d5e14d74b5cb77',
'width' => '300',
),
2 =>
array (
'height' => '64',
'url' => 'https://i.scdn.co/image/ab67616d0000485187d20b9a27d5e14d74b5cb77',
'width' => '64',
),
),
'name' => 'Carpe Diem',
'release_date' => '2020-10-07',
'release_date_precision' => 'day',
'total_tracks' => '12',
'type' => 'album',
'uri' => 'spotify:album:6fG2eFCgUmytQWL6umtsCh',
),
'artists' =>
array (
0 =>
array (
'external_urls' =>
array (
'spotify' => 'https://open.spotify.com/artist/4ovtyvs7j1jSmwhkBGHqSr',
),
'href' => 'https://api.spotify.com/v1/artists/4ovtyvs7j1jSmwhkBGHqSr',
'id' => '4ovtyvs7j1jSmwhkBGHqSr',
'name' => 'Olamide',
'type' => 'artist',
'uri' => 'spotify:artist:4ovtyvs7j1jSmwhkBGHqSr',
),
1 =>
array (
'external_urls' =>
array (
'spotify' => 'https://open.spotify.com/artist/5yOvAmpIR7hVxiS6Ls5DPO',
),
'href' => 'https://api.spotify.com/v1/artists/5yOvAmpIR7hVxiS6Ls5DPO',
'id' => '5yOvAmpIR7hVxiS6Ls5DPO',
'name' => 'Omah Lay',
'type' => 'artist',
'uri' => 'spotify:artist:5yOvAmpIR7hVxiS6Ls5DPO',
),
),
'disc_number' => '1',
'duration_ms' => '171764',
'explicit' => '1',
'external_ids' =>
array (
'isrc' => 'USUYG1330802',
),
'external_urls' =>
array (
'spotify' => 'https://open.spotify.com/track/5DS9LiyEdw2zY8bM6kjjgM',
),
'href' => 'https://api.spotify.com/v1/tracks/5DS9LiyEdw2zY8bM6kjjgM',
'id' => '5DS9LiyEdw2zY8bM6kjjgM
[is_local] => ',
'is_playable' => '1',
'name' => 'Infinity (feat. Omah Lay)',
'popularity' => '73',
'preview_url' => 'https://p.scdn.co/mp3-preview/5159fa17676fc96e32db13b7680f7497d5c2f74d?cid=756f211306ad4c9a934d07c5722790b5',
'track_number' => '3',
'type' => 'track',
'uri' => 'spotify:track:5DS9LiyEdw2zY8bM6kjjgM',
),
1 =>
array (
'album' =>
array (
'album_type' => 'album',
'artists' =>
array (
0 =>
array (
'external_urls' =>
array (
'spotify' => 'https://open.spotify.com/artist/4ovtyvs7j1jSmwhkBGHqSr',
),
'href' => 'https://api.spotify.com/v1/artists/4ovtyvs7j1jSmwhkBGHqSr',
'id' => '4ovtyvs7j1jSmwhkBGHqSr',
'name' => 'Olamide',
'type' => 'artist',
'uri' => 'spotify:artist:4ovtyvs7j1jSmwhkBGHqSr',
),
),
'external_urls' =>
array (
'spotify' => 'https://open.spotify.com/album/6fG2eFCgUmytQWL6umtsCh',
),
'href' => 'https://api.spotify.com/v1/albums/6fG2eFCgUmytQWL6umtsCh',
'id' => '6fG2eFCgUmytQWL6umtsCh',
'images' =>
array (
0 =>
array (
'height' => '640',
'url' => 'https://i.scdn.co/image/ab67616d0000b27387d20b9a27d5e14d74b5cb77',
'width' => '640',
),
1 =>
array (
'height' => '300',
'url' => 'https://i.scdn.co/image/ab67616d00001e0287d20b9a27d5e14d74b5cb77',
'width' => '300',
),
2 =>
array (
'height' => '64',
'url' => 'https://i.scdn.co/image/ab67616d0000485187d20b9a27d5e14d74b5cb77',
'width' => '64',
),
),
'name' => 'Carpe Diem',
'release_date' => '2020-10-07',
'release_date_precision' => 'day',
'total_tracks' => '12',
'type' => 'album',
'uri' => 'spotify:album:6fG2eFCgUmytQWL6umtsCh',
),
'artists' =>
array (
0 =>
array (
'external_urls' =>
array (
'spotify' => 'https://open.spotify.com/artist/4ovtyvs7j1jSmwhkBGHqSr',
),
'href' => 'https://api.spotify.com/v1/artists/4ovtyvs7j1jSmwhkBGHqSr',
'id' => '4ovtyvs7j1jSmwhkBGHqSr',
'name' => 'Olamide',
'type' => 'artist',
'uri' => 'spotify:artist:4ovtyvs7j1jSmwhkBGHqSr',
),
1 =>
array (
'external_urls' =>
array (
'spotify' => 'https://open.spotify.com/artist/68R39izwNAztATrXMOqkJS',
),
'href' => 'https://api.spotify.com/v1/artists/68R39izwNAztATrXMOqkJS',
'id' => '68R39izwNAztATrXMOqkJS',
'name' => 'Bad Boy Timz',
'type' => 'artist',
'uri' => 'spotify:artist:68R39izwNAztATrXMOqkJS',
),
),
'disc_number' => '1',
'duration_ms' => '194000',
'explicit' => '1',
'external_ids' =>
array (
'isrc' => 'USUYG1330809',
),
'external_urls' =>
array (
'spotify' => 'https://open.spotify.com/track/558ULLj8yY2vT8XGtgY0q9',
),
'href' => 'https://api.spotify.com/v1/tracks/558ULLj8yY2vT8XGtgY0q9',
'id' => '558ULLj8yY2vT8XGtgY0q9
[is_local] => ',
'is_playable' => '1',
'name' => 'Loading (feat. Bad Boy Timz)',
'popularity' => '64',
'preview_url' => 'https://p.scdn.co/mp3-preview/7848a9f9ea879e6b1c6618508354e2559678aa8c?cid=756f211306ad4c9a934d07c5722790b5',
'track_number' => '10',
'type' => 'track',
'uri' => 'spotify:track:558ULLj8yY2vT8XGtgY0q9',
),
),
);

$tracks = [];

foreach ($api['tracks'] as $track) {
$_track = [
'artists' => '',
'name' => '',
'album' => '',
'image' => ''
];

$artists = [];
foreach ($track['artists'] as $artist) {
$artists[] = $artist['name'];
}
$_track['artists'] = implode(', ', $artists);

$_track['name'] = $track['name'];
$_track['album'] = $track['album']['name'];
$_track['image'] = $track['album']['images'][2]['url'];

$tracks[] = $_track;
}

var_dump($tracks);

Results in:

array(2) {
[0]=>
array(4) {
["artists"]=>
string(17) "Olamide, Omah Lay"
["name"]=>
string(25) "Infinity (feat. Omah Lay)"
["album"]=>
string(10) "Carpe Diem"
["image"]=>
string(64) "https://i.scdn.co/image/ab67616d0000485187d20b9a27d5e14d74b5cb77"
}
[1]=>
array(4) {
["artists"]=>
string(21) "Olamide, Bad Boy Timz"
["name"]=>
string(28) "Loading (feat. Bad Boy Timz)"
["album"]=>
string(10) "Carpe Diem"
["image"]=>
string(64) "https://i.scdn.co/image/ab67616d0000485187d20b9a27d5e14d74b5cb77"
}
}

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 accessing different parts of multidimensional array

It may help your understanding to visualize this two-dimensional array in two dimensions, sort of like a spreadsheet.

                  [bronze][silver][gold]
[SX- Light weight] 4 5 6
[SS- Light weight] 4 5 6

The foreach loops over the rows. This means that in

foreach ($product as  $name => $value) {

the $value is not a single value, it is a row, an array containing the values of the bronze, silver, and gold columns. So in the first iteration of this loop, for example, $value will contain

array('bronze' => 4, 'silver' => 5, 'gold' => 6)

You can iterate over each column in the row and do something with those values by using another foreach, but if you just need to access a specific column, you can use its key to specify which one you want, like this:

echo $value['bronze'];

Thinking of the contents of a two-dimensional array as rows and columns is a pretty common visualization. In fact, in PHP 5.5+ there is the array_column function, that allows you to pull all of the values from a specific column into a new array.

$bronze = array_column($product, 'bronze');  // for example.

Obviously if the array goes beyond two dimensions, this visualization becomes less useful.

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