Group array values by string in key?
Ok, given this data structure:
array(
'name one' => 'fred',
'desc one' => 'lorem ipsum'
'name two' => 'charles',
'desc two' => 'lorem ipsum'
);
in php, how can I match the numeric value assigned to the ONE or TWO key and return this:
array(
'one' => array('name' => 'fred', 'desc' => 'lorem ipsum'),
'two' => array('name' => 'charles' , 'desc => 'lorem ipsum')
);
+3
source to share
2 answers
This is a straightforward logical problem and this is how you do it ( I'm sure there is a faster alternative, but this does exactly what you need ):
$new = array();
foreach($array as $key => $val) {
list($item, $number) = explode(' ', $key);
$new[$number][$item] = $val;
}
We use list()
and explode()
in the above example to get the required variables. Namely the number "one" or "two" and the name of the element, essentially "name" and "desc".
EDIT
As Lajos said, if $new[$number]
not set, this version will sort and create the required array:
$new = array();
foreach($array as $key => $val) {
list($item, $number) = explode(' ', $key);
// if the array isn't set
if(!isset($new[$number])) $new[$number] = array();
$new[$number][$item] = $val;
}
+5
source to share