Create Multidimensional Array Using a Foreach Loop

create multidimensional array using a foreach loop

You're aaalmost there. Just add the level to the array creation :)

$levels = array('low', 'medium', 'high');
$attributes = array('fat', 'quantity', 'ratio', 'label');

foreach ($levels as $key => $level):
foreach ($attributes as $k =>$attribute):
$variables[$level][] = $attribute . '_' . $level; // changed $variables[] to $variables[$level][]
endforeach;
endforeach;

echo '<pre>' . print_r($levels,1) . '</pre>';
echo '<pre>' . print_r($variables,1) . '</pre>';

Output

Array
(
[low] => Array
(
[0] => fat_low
[1] => quantity_low
[2] => ratio_low
[3] => label_low
)

[medium] => Array
(
[0] => fat_medium
[1] => quantity_medium
[2] => ratio_medium
[3] => label_medium
)

[high] => Array
(
[0] => fat_high
[1] => quantity_high
[2] => ratio_high
[3] => label_high
)

)

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);

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
)

)

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 does foreach loop works with 2d array?

2D string array is not optimal choice for your task ("build a store with car"). c# is object-oriented language, so you can have a class for Car, and a class for Store with list of cars - easy to build, maintain, modify:

public class Car
{
public string Brand { get; set; }
public double Price { get; set; }
public int Year { get; set; } // new Car property
}

public class CarStore
{
public IList<Car> Cars { get; } = new List<Car>();
}

then use for loop or foreach - both will work

public static void Main()
{
var store = new CarStore
{
Cars =
{
new Car { Brand = "Ford", Year = 2021, Price = 120000 },
new Car { Brand = "Chevrolet", Year = 2020, Price = 100000 },
}
};
foreach(var car in store.Cars)
{
Console.WriteLine(car.Price.ToString("C"));
}
// new car arrived:
store.Cars.Add(new Car { Brand = "Rolls-Royce", Year = 2022, Price = 1_000_000 });
}

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

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

}


Related Topics



Leave a reply



Submit