Reputation: 43
I am trying to sort the following arrays.
Array(s)
$fruits = array(
'mango',
'mango red',
'mango yellow',
'orange',
'banana',
'apple',
'apple red',
'apple green',
);
What I have done:
$data = array_flip( $fruits ); // flip array
$data = array_fill_keys( array_keys( array_flip( $data ) ), 'array(),' ); // fill array value: "array(),"
print_r( $data );
I want this result:
$fruits = array(
'mango' => array(
'red' => array(),
'yellow' => array(),
),
'orange' => array(),
'banana' => array(),
'apple' => array(
'red' => array(),
'green' => array(),
),
);
Does anybody know how to do this?
Upvotes: 1
Views: 59
Reputation: 92884
Use the following approach(for your current array):
$result = [];
foreach ($fruits as $fruit) {
$parts = explode(' ', $fruit);
if (count($parts) == 1) {
$result[$fruit] = [];
} elseif (isset($result[$parts[0]])) {
$result[$parts[0]][$parts[1]] = [];
}
}
print_r($result);
Upvotes: 1
Reputation: 782166
Loop through the array, and split the string. Then recursively create nested arrays.
$result = array();
foreach ($fruits as $f) {
$f_array = explode(' ', $f);
$start = &$result;
foreach ($f_array as $word) {
if (!isset($start[$word])) {
$start[$word] = array();
}
$start = &$start[$word];
}
}
var_dump($result);
Upvotes: 1