简体   繁体   中英

What's the most elegant way to enumerate keys on a multidimensional PHP array from the value of a contained element's key?

Say I have a multidimensional, numeric zero-indexed array that looks like this:

$oldArray = (
    0 => array("importantKey" => "1", "otherKey" => "someValue"),
    1 => array("importantKey" => "4", "otherKey" => "someValue"),
);

What's the cleanest way to map this to the following, provided I can be sure of the uniqueness of "importantKey"

$newArray = (
    1 => array("otherKey" => "someValue"),
    4 => array("otherKey" => "someValue"),
);

This is useful when retrieving multiple rows from a database after doing a GROUP BY clause on "importantKey"

Try this

$newArray = array_reduce($oldArray, function($res, $val) {
    $res[$val['importantKey']]['otherKey'] = $val['otherKey'];

    return $res;
}, array());

Is this elegant enought? :)

$data=array();
foreach($oldArray as $k=>$v)
{
   if(isset($v['importantKey']) && isset($v['otherKey']))
   {
      $data[$v['importantKey']]=array('otherKey' =>$v['otherKey']);
   }
}

echo "<pre />";
print_r($data);

Depends on how you define "clean". How about this?

$newArray = array_combine(
    array_map(function (array $i) { return $i['importantKey']; }, $oldArray),
    array_map(function (array $i) { return array_diff_key($i, array_flip(['importantKey'])); }, $oldArray)
);

This takes a few more iterations than you'd need using a straight forward foreach though.

This is an easy solution to copy the entire array except the key to an array. Why would you want PK as an array index anyway? A PHP array isn't a database row, and metadata for the array shouldn't be database data.

$new = array();
foreach($old as $value) {
    $newInner = $value;
    unset($newInner["importantKey"])
    $new[$value["importantKey"]] = array($newInner);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM