最好在php中的特殊键上更改数组结构

时间:2016-12-26 16:12:29

标签: php arrays

我需要对数组做一些事情并且无法弄清楚如何。 我有这个数组:

$arr = array(
       "0" => array("var_id" => 11, "var_name" => 'london', "var_price" => 250),
       "1" => array("var_id" => 22, "var_name" => 'moscow', "var_price" => 320),
       "2" => array("var_id" => 33, "var_name" => 'chicago', "var_price" => 99),
       "3" => array("var_id" => 11, "var_name" => 'london', "var_price" => 140),
       "4" => array("var_id" => 44, "var_name" => 'amsterdam', "var_price" => 555),
       "5" => array("var_id" => 33, "var_name" => 'chicago', "var_price" => 663),
       "6" => array("var_id" => 33, "var_name" => 'chicago', "var_price" => 777)
    );

我希望能够在这个例子中改变阵列结构我需要只有4个主要城市的新阵列:伦敦,莫斯科,芝加哥,阿姆斯特丹,唯一的关键是var_id,里面是这样的价格数组:

$arr_new = array(
   "0" => array("var_id" => 11, "var_name" => 'london', "var_price" => array("0" => 250,"1" => 140)),
   "1" => array("var_id" => 22, "var_name" => 'moscow', "var_price" => array("0" => 320)),
   "2" => array("var_id" => 33, "var_name" => 'chicago', "var_price" => array("0" => 99,"1" => 663,"2" => 777)),
   "3" => array("var_id" => 44, "var_name" => 'amsterdam', "var_price" => array("0" => 555))
);

如果有任何php类或函数可以做到(我更喜欢上课)。 这是我制作的一个很好的截图:

my arrays dbug

1 个答案:

答案 0 :(得分:1)

您可以使用foreach循环执行此操作:

$array = array(
   "0" => array("var_id" => 11, "var_name" => 'london', "var_price" => 250),
   "1" => array("var_id" => 22, "var_name" => 'moscow', "var_price" => 320),
   "2" => array("var_id" => 33, "var_name" => 'chicago', "var_price" => 99),
   "3" => array("var_id" => 11, "var_name" => 'london', "var_price" => 140),
   "4" => array("var_id" => 44, "var_name" => 'amsterdam', "var_price" => 555),
   "5" => array("var_id" => 33, "var_name" => 'chicago', "var_price" => 663),
   "6" => array("var_id" => 33, "var_name" => 'chicago', "var_price" => 777)
);

$final_arr = [];

foreach ($array as $key => $arr) {
    $final_arr[$arr['var_name']]['var_name'] = $arr['var_name'];
    $final_arr[$arr['var_name']]['var_id'] = $arr['var_id'];
    $final_arr[$arr['var_name']]['var_price'][] = $arr['var_price'];
}

var_dump(array_values($final_arr));

预期的输出将是这样的:

array:4 [
  0 => array:2 [
    "var_id" => 11
    "var_price" => array:2 [
      0 => 250
      1 => 140
    ]
  ]
  1 => array:2 [
    "var_id" => 22
    "var_price" => array:1 [
      0 => 320
    ]
  ]
  2 => array:2 [
    "var_id" => 33
    "var_price" => array:3 [
      0 => 99
      1 => 663
      2 => 777
    ]
  ]
  3 => array:2 [
    "var_id" => 44
    "var_price" => array:1 [
      0 => 555
    ]
  ]
]