将对象内的相同数组值分组为相同的键

时间:2013-02-25 14:14:12

标签: php arrays multidimensional-array

我有以下数组:

[1]=>
  array(2) {
    [0]=>
        object(stdClass)#23 (7) {
          ["AddressesTableID"]=> string(1) "8"
          ["AccreditNo"]=> string(13) "5129876de28ff"
          ["Type"]=> string(4) "home"
          ["Street"]=> string(34) "Wallace, Village, Under the bridge"
          ["Municipality"]=> string(8) "Tortuous"
          ["Province"]=> string(8) "Sardonic"
          ["ContactNo"]=> string(8) "92012010"
        }
    [1]=>
        object(stdClass)#24 (7) {
          ["AddressesTableID"]=> string(1) "9"
          ["AccreditNo"]=> string(13) "5129876de28ff"
          ["Type"]=> string(6) "office"
          ["Street"]=> string(25) "Rasputin Query, Palpitate"
          ["Municipality"]=> string(7) "Opulent"
          ["Province"]=> string(6) "Number"
          ["ContactNo"]=> string(8) "29101011"
    }
  }

你能帮我解决一下如何将其转化为:

哪里将所有值分组为类似的键?

["AccreditNo"]=> array(2) { "5129876de28ff", "GKIJUGUIKGI" }
["Type"]=> array(2) { "home", "home" }
["Street"]=> ...
["Municipality"]=> ... 
["Province"]=> ...
["ContactNo"]=> ...

2 个答案:

答案 0 :(得分:2)

尝试:

$input  = array( /* your input data*/ );
$output = array();

foreach ( $input as $data ) {
  foreach ( $data as $key => $value ) {
    if ( !isset($output[$key]) ) {
      $output[$key] = array();
    }
    $output[$key][] = $value;
  }
}

答案 1 :(得分:2)

您可以使用array_merge_recursive()函数,如下所示:

$arr = array_merge_recursive($arr1, $arr2)

有关详细信息,请参阅此处:http://www.php.net/manual/en/function.array-merge-recursive.php