在下面的示例中,我循环遍历具有以下输出的 MySQL 查询的结果:
这是我迄今为止拥有的 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/