PHP按值合并数组,放入表 - 最佳结构?

时间:2016-04-02 07:50:20

标签: php arrays

我有以下结果数组:

 Array
  (
      // 1st big array of results
      [0] => Array
          (
              [0] => Array
                  (
                      [customer] => John
                      [shop_name] => shop1
                      [shop_address] => address1
                  )

              [1] => Array
                  (
                      [customer] => John
                      [shop_name] => shop2
                      [shop_address] => address2
                  )

              [2] => Array
                  (
                      [customer] => Mark
                      [shop_name] => shop1
                      [shop_address] => address1
                  )

          )

      // 2nd big array of results
      [1] => Array
          (
              [0] => Array
                  (
                      [customer] => Cathy
                      [shop_name] => shop3
                      [shop_address] => address3
                  )

              [1] => Array
                  (
                      [customer] => Cathy
                      [shop_name] => shop4
                      [shop_address] => address4
                  )

              [2] => Array
                  (
                      [customer] => Maria
                      [shop_name] => shop3
                      [shop_address] => address3
                  )

          )

  )

每个大型结果中的每个客户都有{strong>唯一对 shop_nameshop_address

我想做什么

我想将第一大数组的每个customer放在一个<th></th>中,而将其shop_nameshop_address放在个人<td></td>中1}}像这样:

What I'd like to do - Table IMG

当然,重复第二大阵列的过程。

我是否拥有最佳的阵列结构?

或许我应该将每个customer放在自己的数组中:

// Give each 'customer' its own array

foreach ($array[0] as $result) {
   $array_by_customer[$result['customer']][] = $result;
}

但是你可以看到我只能为array[0] - 第一大结果做到这一点。

Array by customer - PHP Fiddle

1 个答案:

答案 0 :(得分:0)

我认为你的方法很好:为每位顾客制作一个阵列。

我建议你对数组中的所有结果执行此操作,这就是它!

foreach ($array as $big_array_key => $results) {
    foreach ($results as $result) {
        $arrays_by_customer[$big_array_key][$result['customer']][] = $result;
    }
}

然后你的$ arrays_by_customer将包含两个大数组:一个用于初始大数组。