如何在php中键入映射​​数组

时间:2015-07-29 05:57:07

标签: php arrays foreach

我有一个数组如下

array(2) { ["name"]=> string(36) "newyork" ["categoryid"]=> string(1) "4" }                                                                                                                                                                                                            
array(2) { ["name"]=> string(24) "michigun" ["categoryid"]=> string(1) "4" } 
array(2) { ["name"]=> string(27) "canada" ["categoryid"]=> string(1) "5" }             
array(2) { ["name"]=> string(35) "manhatten" ["categoryid"]=> string(1) "5"   
}

我希望有一个新阵列,我将拥有

 {"4" => newyork,michigun}
 {"5" => canada,manhatten}

..怎么办?请帮助。

3 个答案:

答案 0 :(得分:4)

您可以使用循环并构建数组 -

$new = array();
foreach($your_array as $array) {
   if(array_key_exists($array['categoryid'], $new)) { // if categoryid is already set the concatenate the name
       $new[$array['categoryid']] = $new[$array['categoryid']] . ',' . $array['name'];
   } else { // set the name
       $new[$array['categoryid']] = $array['name'];
   }
}

答案 1 :(得分:4)

如果不介意使用外部库,那么使用ouzo-goodies非常简单:

Arrays::groupBy($array, Functions::extractField('categoryid'));

您可以更进一步用逗号连接姓名:

$result = Arrays::groupBy($array, Functions::extractField('categoryid'));
Arrays::map($result, function($value) {
    return Joiner::on(',')->mapValues(Functions::extractField('name'))->join($value);
});

答案 2 :(得分:1)

使用PHP 5.4数组语法:[]而不是array()

数据

$arr = [
  [
    "name" => "newyork",
    "categoryid" => "4"
  ],
  [
    "name" => "michigun",
    "categoryid" => "4"
  ],
  [
    "name" => "canada",
    "categoryid" => "5"
  ],
    [
    "name" => "manhatten",
    "categoryid" => "5"
  ],
];

解析

$result = [];

foreach ($arr as $el) {
  if (array_key_exists($el['categoryid'], $result)) {
    $result[$el['categoryid']] = $result[$el['categoryid']] . ',' . $el['name'];
  } else {
   $result[$el['categoryid']] = $el['name'];
  }
}


print_r($result);

结果

Array ( [4] => newyork,michigun [5] => canada,manhatten )