How to Convert a Single Array into a Multidimensional Array in PHP

How to convert a Single Array into a multidimensional array in PHP?

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

Convert single array into multidimensional array in PHP?

It wasn't quite as simple as I had imagined to begin with. The key to it was doing the process backwards - starting with the last array and then wrapping it in more arrays until you get back to the top level.

$array = array("first", "second", "third");
$newArr = array();

//loop backwards from the last element
for ($i = count($array)-1; $i >= 0 ; $i--)
{
$arr = array();
if ($i == count($array)-1) {
$val = "example";
$arr[$array[$i]] = $val;
}
else {
$arr[$array[$i]] = $newArr;
}
$newArr = $arr;
}

var_dump($newArr);
echo "-------".PHP_EOL;
echo $newArr["first"]["second"]["third"];

Demo: http://sandbox.onlinephpfunctions.com/code/0d7fa30fde7126160fbcc0e80e5727f17b19e39f

Convert multidimensional array into single array

Assuming this array may or may not be redundantly nested and you're unsure of how deep it goes, this should flatten it for you:

function array_flatten($array) { 
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, array_flatten($value));
}
else {
$result[$key] = $value;
}
}
return $result;
}

PHP convert one dimensional array into multidimensional

Iterate the array of keys and use a reference for the end of the chain:

$arr = array();
$ref = &$arr;
foreach ($tmpArr as $key) {
$ref[$key] = array();
$ref = &$ref[$key];
}
$ref = $key;
$tmpArr = $arr;

Convert a one dimensional array to two dimensional array

Assuming you want to remove all quotation marks as per your question:

$oldArray = array('id,"1"', 'name,"abcd"', 'age,"30"')
$newArray = array();
foreach ($oldArray as $value) {
$value = str_replace(array('"',"'"), '', $value);
$parts = explode(',', $value);
$newArray[] = $parts;
}

How can I convert a multidimensional array into one level array?

It looks like you want all sub array values to be in the single array.

$singleArray = [];
foreach($multiarray as $array) {
$singleArray = array_merge($singleArray, array_values($array));
}

This may contain some values as a duplicate. To clean them up you can do

$uniqueValues = array_unique($singleArray);


Related Topics



Leave a reply



Submit