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".

Example




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;
}

      

Example

+5


source


Something like that:



$target = array();
foreach ($elements as $k => $v) {
    $keys = explode(" ", $k);
    if (!isset($target[$keys[1]])) {
        $target[$keys[1]] = array();
    }
    $target[$keys[1]][$keys[0]] = $v;
}

      

+3


source







All Articles