I want to restructure an associative array of associative arrays so that the original second level keys become the new first level keys and the original first level keys become the delimited prefix for each value. Only the values of the first occurring second level key should be retained (and prefixed).
$array = [
'strongfruit' => [
'apple' => 'say:helloworld',
'banana' => 'say:omgdude',
'grape' => 'say:dope',
'alienfruit' => 'say:ganja',
],
'weakfruit' => [
'apple' => 'say:helloworld',
'banana' => 'say:omgdude',
'grape' => 'say:dope',
'orange' => 'say:yeahdude',
],
'moreweakerfruit' => [
'apple' => 'say:helloworld',
'anotheralienfruit' => 'say:yeahhellyeah'
],
];
to be something like
[
'apple' => 'strongfruit:say:helloworld', #from strong
'banana' => 'strongfruit:say:omgdude', #from strong
'grape' => 'strongfruit:say:dope', #from strong
'alienfruit' => 'strongfruit:say:ganja', #from strong
'orange' => 'weakfruit:say:yeahdude', #from weak
'anotheralienfruit' => 'moreweakerfruit:say:yeahhellyeah' #from weaker
]
Yesterday, I asked about joining arrays, preserving different value, pick one if same. with php
Here's how we join them to get the order:
$result = array();
foreach ($array as $value) {
$result += $value;
}
The difference is how can we append the key to a value in an array?
$newarray = array();
foreach ($array as $type => $fruit) {
foreach ($fruit as $fruitname => $string) {
//if the fruit is not already in the new array
if (!isset($newarray[$fruitname])) {
$newarray[$fruitname] = $type . ':' . $string;
}
}
}