php - 对 foreach 中的项目进行分组并创建数组

标签 php mysql arrays foreach

在下面的示例中,我循环遍历具有以下输出的 MySQL 查询的结果:

enter image description here

这是我迄今为止拥有的 PHP:

foreach ($customers as $customer) {

  if($customer['innumber'] != null){

      $chartInbound['name'] = $customer['name'];
      $chartInbound['label'] = $customer['innumber'];
      $chartInbound['count'] = $customer['count'];
      $chartInbound['customerid'] = $customer['id'];

      array_push($out['chartInbound'], $chartInbound);
   }
}

print_r($out['chartInbound']); 的输出为:

Array
(
[0] => Array
    (
        [name] => 1st Online Solutions
        [label] => 01-02
        [count] => 577
        [customerid] => 129
    )

[1] => Array
    (
        [name] => Bookngo
        [label] => 01-02
        [count] => 2
        [customerid] => 95
    )

[2] => Array
    (
        [name] => Boutixury
        [label] => 07
        [count] => 1
        [customerid] => 14
    )

[3] => Array
    (
        [name] => Cruise Village
        [label] => 01-02
        [count] => 16
        [customerid] => 25
    )

[4] => Array
    (
        [name] => Cruise Village
        [label] => 00
        [count] => 1
        [customerid] => 25
    )

[5] => Array
    (
        [customer] => Cruise Village
        [label] => 07
        [countInbound] => 16
        [minsInbound] => 125
        [customerid] => 25
    )
  ...................
)

所需的输出应该是:

Array
(
[0] => Array
    (
        [name] => 1st Online Solutions
        [01-02] => 577
        [customerid] => 129
    )

[1] => Array
    (
        [name] => Bookngo
        [01-02] => 2
        [customerid] => 95
    )

[2] => Array
    (
        [name] => Boutixury
        [07] => 1
        [customerid] => 14
    )

[3] => Array
    (
        [name] => Cruise Village
        [07] => 16
        [00] => 1
        [01-02] => 16
        [customerid] => 25
    )
  ...................
)

怎样才能达到上述结果?

最佳答案

你可以做到这一点 -

$chartInbound = array(); 
foreach ($customers as $customer) {

  if($customer['innumber'] != null){
      if(array_key_exists([$customer['id']], $chartInbound)) {
         $chartInbound[$customer['id']][$customer['innumber'] = $customer['count'];
      } else {
         $chartInbound[$customer['id']]['name'] = $customer['name'];
         $chartInbound[$customer['id']][$customer['innumber'] = $customer['count'];
         $chartInbound[$customer['id']]['customerid'] = $customer['id'];
      }
   }
}

关于php - 对 foreach 中的项目进行分组并创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30161911/

相关文章:

javascript - 在字符串连接内执行映射函数

php - json_decode 不适用于我的字符串

php - 在 laravel 5.1 中获取 fullUrl

javascript - 无法正确从 html(js) 检索 cookie 值到 php 文件

php - Laravel SQL 查询返回重复项

mysql - 我如何使用 Erlang 的 Yaws Web 服务器访问 MySQL

arrays - Ruby 减去两个字符串数组

php - CakePHP 连接在浏览器中被拒绝

mysql使用返回x行数的子查询更新或插入到另一个表

arrays - 使用的变量。但错误仍然是 "variable x not used"