我想将列表与其他人进行比较,以便在他们的数字(id_article)相同时进行合并。 在我的例子中,我想获得这个最终的数组列表:
* 最终*
Array
(
[0] => Array
(
[id_article] => 1
[quantite] => 5
)
[1] => Array
(
[id_article] => 3
[quantite] => 1
)
}
INITIAL
Array
(
[0] => Array
(
[id_article] => 1
[quantite] => 2
)
[1] => Array
(
[id_article] => 1
[quantite] => 3
)
[2] => Array
(
[id_article] => 3
[quantite] => 1
)
)
我尝试使用next()和current()但在这种情况下不起作用。
提前感谢您的帮助,建议或其他示例。
答案 0 :(得分:2)
你必须做一些循环工作:
$result = array();
foreach ($array as $value) {
if (isset($result[$value['id_article']])) {
$result[$value['id_article']] += $value['quantite'];
} else {
$result[$value['id_article']] = $value['quantite'];
}
}
$output = array();
foreach ($result as $id => $value) {
$output[] = array('id_article' => $id, 'quantite' => $value);
}
答案 1 :(得分:1)
尝试这个
echo "<pre>";
$arr_input = array(
array
(
"id_article" => 1,
"quantite" => 2
),
array
(
"id_article" => 1,
"quantite" => 3
),
array
(
"id_article" => 3,
"quantite" => 1
)
);
$arr_temp = array();
foreach($arr_input as $arr)
{
if(isset($arr_temp[$arr['id_article']]))
{
$arr_temp[$arr['id_article']] += $arr['quantite'];
}
else
{
$arr_temp[$arr['id_article']] = $arr['quantite'];
}
}
$arr_ouput = array();
foreach($arr_temp as $key=>$val)
{
$arr_output[] = array("id_article" => $key, "quantite" => $val);
}
print_r($arr_output);
答案 2 :(得分:0)
$a = array(
array(
'id_article' => 1,
'quantite' => 2,
),
array(
'id_article' => 1,
'quantite' => 3,
),
array(
'id_article' => 3,
'quantite' => 1,
),
);
$b = array();
foreach ($a as $k => $v) {
if (array_key_exists($v['id_article'], $b)) {
$b[$v['id_article']]['quantite'] += $v['quantite'];
} else {
$b[$v['id_article']] = $v;
}
}
return array_values($b);