So I have an array that looks like this:
[98] => Array
(
[City] => Caracas
[Country] => Venezuela
[Continent] => Latin America
)
[99] => Array
(
[City] => Cairo
[Country] => Egypt
[Continent] => Middle East
)
[105] => Array
(
[City] => Abu Dhabi
[Country] => United Arab Emirates
[Continent] => Middle East
)
[106] => Array
(
[City] => Dubai
[Country] => United Arab Emirates
[Continent] => Middle East
)
[107] => Array
(
[City] => Montreal
[Country] => Canada
[Continent] => North America
)
I am trying to sort this array into a multi-dimensional array, so that it outputs something like:
Continent
- Country Name
-- Cities under Every Country
I am using PHP. Can anyone point me to a good starting point as to how I should go about doing this?
This single line would do that: $array = array_column($array, 'plan'); The first argument is an array | The second argument is an array key.
You can create a multidimensional array by creating a 2-D matrix first, and then extending it. For example, first define a 3-by-3 matrix as the first page in a 3-D array. Now add a second page. To do this, assign another 3-by-3 matrix to the index value 2 in the third dimension.
PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people. The dimension of an array indicates the number of indices you need to select an element.
PHP Multidimensional array is used to store an array in contrast to constant values. Associative array stores the data in the form of key and value pairs where the key can be an integer or string. Multidimensional associative array is often used to store data in group relation.
$array = array(
98 => array(
'City' => 'Caracas',
'Country' => 'Venezuela',
'Continent' => 'Latin America',
),
99 => array(
'City' => 'Cairo',
'Country' => 'Egypt',
'Continent' => 'Middle East',
),
105 => array(
'City' => 'Abu Dhabi',
'Country' => 'United Arab Emirates',
'Continent' => 'Middle East',
),
106 => array(
'City' => 'Dubai',
'Country' => 'United Arab Emirates',
'Continent' => 'Middle East',
),
107 => array(
'City' => 'Montreal',
'Country' => 'Canada',
'Continent' => 'North America',
)
);
$newArray = array();
foreach ($array as $row)
{
$newArray[$row['Continent']][$row['Country']][] = $row['City'];
}
print_r($newArray);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With