Array of Associative Arrays in PHP
Very often in PHP, arrays appear that contain a set of some entities, for example, a list of users or a list of products.
Here is an example of such an array:
<?php
$users = [
[
'name' => 'user1',
'age' => 31,
'salary' => 1000,
],
[
'name' => 'user2',
'age' => 32,
'salary' => 2000,
],
[
'name' => 'user3',
'age' => 33,
'salary' => 3000,
],
];
?>
As you can see, here we are dealing with an array
of associative arrays. Despite the fact that
this array is two-dimensional, as a rule,
one foreach
loop is used to iterate through it,
which iterates over the subarrays. And the parts of the subarrays themselves
are simply retrieved by key and output in the required
order and format.
Let's output a column of our employees in some format as an example:
<?php
foreach ($users as $user) {
echo $user['name'] . ': ' . $user['salary'] . '$, ' . $user['age'] . '<br>';
}
?>
The following array is given:
<?php
$products = [
[
'name' => 'мясо',
'price' => 100,
'amount' => 5,
],
[
'name' => 'овощи',
'price' => 200,
'amount' => 6,
],
[
'name' => 'фрукты',
'price' => 300,
'amount' => 7,
],
];
?>
Using this array, output a column of products in some format you come up with.