I have this array:
Array
(
[LLLLLLL:] => Array
(
[ brand1:] => Array
(
[people: (100%)] => Array
(
)
[countries: (90%)] => Array
(
)
[yyyy: (80%)] => Array
(
)
[languages: (70%)] => Array
(
)
)
[ brand2:] => Array
(
[people: (60%)] => Array
(
)
[countries: (50%)] => Array
(
)
[yyyy: (40%)] => Array
(
)
[languages: (30%)] => Array
(
)
)
)
)
How can I re-arrange my array in order to have this:
array(
array(
('LLLLLLL') => 'people',
('BRAND1') => '100%',
('BRAND2') => '60%'),
array(
('LLLLLLL') => 'countries',
('BRAND1') => '90%',
('BRAND2') => '50%')
array(
('LLLLLLL') => 'yyyy',
('BRAND1') => '80%',
('BRAND2') => '50%')
array(
('LLLLLLL') => 'languages',
('BRAND1') => '70%',
('BRAND2') => '30%',
I have no idea, how to, for example, move the string after ':' on key to the value and than re-arrange in the different order. How can this be done?
I think this should do it. Please note that it was not tested:
$result = array();
foreach ($initialArray as $lll => $brands) {
$lll = rtrim($lll, ':');
foreach ($brands as $brandName => $brandValues) {
$brandName = strtoupper(preg_replace('/[\s:]/', '', $brandName));
$values = array_keys($brandValues);
foreach ($values as $value) {
preg_match('/([a-z]*): \(([0-9]*%)\)/', $value, $matches);
if (!isset($result[$matches[1]])) {
$result[$matches[1]] = array($lll => $matches[1]);
}
$result[$matches[1]][$brandName] = $matches[2];
}
}
}
You can use regexp + array_map for it.
$datos = Array(
'LLLLLLL:' => Array(
'brand1:' => Array(
'people: (100%)' => Array
(
),
'countries: (90%)' => Array
(
),
'yyyy: (80%)' => Array
(
),
'languages: (70%)' => Array
(
)
),
'brand2:' => Array(
'people: (60%)' => Array
(
),
'countries: (50%)' => Array
(
),
'yyyy: (40%)' => Array
(
),
'languages: (30%)' => Array
(
)
)
)
);
$datos = array_map(function($row) {
$ret = array();
foreach ($row as $key => $items) {
foreach ($items as $dato => $vacio) {
if (preg_match('/([^:]+): \(([^\)]+)\)/i', $dato, $coincidencias)) {
$pos = $coincidencias[1];
if (!isset($ret[$pos]))
$ret[$pos] = array();
$ret[$pos][$key] = $coincidencias[2];
}
}
}
return $ret;
}, $datos);
echo '<pre>' . print_r($datos, true);
Is not completed, but you can go in this way.