在计数中添加同一数组中的第二个键值



阵列$test_count

array ( 0 => array ( 0 => array ( 'it_id' => '212', 'item' => 'Item 1', 'quantity' => '5', ), 1 => array ( 'it_id' => '1206', 'item' => 'Item 2', 'quantity' => '1', ), 2 => array ( 'it_id' => '212', 'item' => 'Item 1', 'quantity' => '1', ), ), )

若同一数组it_id相同,若同一项在数组中不止一次,我需要输出键值公共值。每个项目都有it_id(表示id(和值,item(表示name(和值、quantity和值,而第二个项目也是如此。。。

目前的输出示例:

Item id : 212 Key quantity: 2
Item id : 1206 Key quantity: 1

输出代码:

foreach($test_count as $tempo => $lol){
foreach ($lol  as $value1) {
$numbers1[$value1[it_id]]++;
}
foreach ($numbers1 as $key1 => $value1) {
if ($value1 > 1){
echo '<font style="color:red;"> Item id : '.$key1.' Key quantity: '.$value1.'</font><br/>';
}else{
echo 'Item id : '.$key1.' Key quantity: '.$value1.'<br/>';
}
}
}

目前,我可以使用id_it在这个数组中找到多个项,并显示其中有多少项在数组中,但是完全不知道如何计算数量,如何从同一数组中提取多个键。要得到这样的结果:

物品id:212关键数量:2物品1数量:7

物品id:1206关键数量:1物品2数量:1

已解决,检查答案

小奖励,如果您不想在数组中看到结果,而是想以几乎用户友好的方式看到结果,下面是来自结果的表代码:

代码

echo '<table rules="all" border="1">';
foreach($out as $name => $ar) {
foreach($ar as $v1 => $v2) {
echo sprintf('<tr><td>%s</td><td>%s</td><td>%s</td></tr>'."rn",
$name, $v1, $v2);           
}
}
echo '</table>';

您只需在第一个循环中添加一个额外的增量来跟踪项目计数,如下所示:

<?php
$out = array();
foreach ($data[0] as $entry) {
$id = $entry['it_id'];
// Ensure the output key we're going to increment actually exists...
if (!isset($out[$id])) {
$out[$id] = array('item_id' => $id, 'key_quantity' => 0, 'item_quantity' => 0);
}
$out[$id]['key_quantity'] += 1;
$out[$id]['item_quantity'] += $entry['quantity'];
}

这将为您提供具有以下结构的$out阵列:

array (
212 => 
array (
'item_id' => '212',
'key_quantity' => 2,
'item_quantity' => 6
),
1206 => 
array (
'item_id' => '1206',
'key_quantity' => 1,
'item_quantity' => 1
)
)

相关内容

最新更新