You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中输出两个数组时如何保留重复项并得到正确结果

问题:数组合并时保留重复项并正确关联对应重量数据

首先展示你数据库中的原始数据:

重量(kg)仓库数量门店数量
25.20.1510.5.100.3.10

你当前使用的PHP代码如下:

<?php
$store = explode('.', $data->store_quantity);
$kilos = explode('.', $data->kilos);

$arr_of_store = array();
$arr_of_kilos = array();

foreach($store as $store){
    $arr_of_store[] = $store;
}

foreach($kilos as $kilos){
    $arr_of_kilos[] = $kilos;
}

echo "Stacks in store: ";

$array_together = array_combine($arr_of_store,$arr_of_kilos);
foreach($array_together as $arr_of_store => $arr_of_kilos){
    echo $arr_of_store.' sacks of '.$arr_of_kilos.'kg'.'<br>';
}

echo "<br>";
echo "Stacks in warehouse: ";

$warehouse = explode('.', $data->warehouse_quantity);
$kilos2 = explode('.', $data->kilos);

$arr_of_ware = array();
$arr_of_kilos2 = array();

foreach($warehouse as $warehouse){
    $arr_of_ware[] = $warehouse;
}

foreach($kilos2 as $kilos2){
    $arr_of_kilos2[] = $kilos2;
}

$array_together2 = array_combine($arr_of_ware,$arr_of_kilos2);

foreach($array_together2 as $arr_of_ware => $arr_of_kilos2){
    echo $arr_of_ware.' sacks of '.$arr_of_kilos2.'kg'.'<br>';
}

?>

你的预期输出:

Stacks in store: 
0 sacks of 25kg
3 sacks of 20kg
10 sacks of 15kg

Stacks in warehouse: 
10 sacks of 25kg
5 sacks of 20kg
10 sacks of 15kg

实际得到的输出:

Stacks in store: 
0 sacks of 25kg
3 sacks of 20kg
10 sacks of 15kg

Stacks in warehouse: 
10 sacks of 15kg
5 sacks of 20kg

你尝试使用concat()函数却收到错误:Call to undefined function concat(),想要知道如何实现预期的输出效果。


问题根源

问题出在你使用array_combine()这个函数上:它要求第一个参数(键数组)的所有元素必须是唯一的。当仓库数量数组里有两个10时,第二个10会覆盖第一个10对应的键值对,导致最终合并后的数组丢失了第一个10对应的25kg条目,还把第二个10错误关联到了15kg上。

另外,PHP里并没有内置的concat()函数,你可能混淆了其他语言的方法,不过我们根本不需要这个函数就能解决问题。

解决方案:通过索引遍历关联数据

因为重量数组、门店数量数组、仓库数量数组的元素是按顺序一一对应的(第一个重量对应第一个数量,以此类推),我们可以直接通过索引来遍历,完全不需要用array_combine(),这样不管数量有没有重复,都能正确关联对应的重量。

修改后的代码如下:

<?php
// 拆分数据为数组,变量名更清晰,避免循环中覆盖原变量
$storeQuantities = explode('.', $data->store_quantity);
$warehouseQuantities = explode('.', $data->warehouse_quantity);
$weights = explode('.', $data->kilos);

echo "Stacks in store: <br>";
// 遍历索引,关联数量和对应位置的重量
foreach ($storeQuantities as $index => $quantity) {
    echo $quantity . ' sacks of ' . $weights[$index] . 'kg<br>';
}

echo "<br>";
echo "Stacks in warehouse: <br>";
foreach ($warehouseQuantities as $index => $quantity) {
    echo $quantity . ' sacks of ' . $weights[$index] . 'kg<br>';
}
?>

代码说明

  1. 优化了变量命名,避免原代码中循环变量覆盖原数组变量的问题(比如你之前用foreach($store as $store),这会导致原数组被覆盖,是不良编码习惯)。
  2. 直接通过foreach的索引参数$index,把每个位置的数量和对应的重量关联起来,确保每个条目都被保留,不会因为重复值被覆盖。
  3. 去掉了原代码中冗余的数组复制操作(explode()已经直接返回数组,不需要再循环存入新数组)。

这样运行后就能得到你想要的预期输出啦!


内容的提问来源于stack exchange,提问作者NeedHalp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 17:15:48