我很难弄清楚如何实现这一点。我有一个数组
$arr = array("purchase_order_details_id"=>array(
0=>"POD1",
1=>"POD1",
2=>"POD2",
),
"quantity_received"=>array(
0=>5,
1=>10,
2=>20
)
);
我想将数组拆分为两个。这样的事情。
$pod_2 = array("purchase_order_details_id"=>array(
0=>"POD1",
1=>"POD1"
),
"quantity_received"=>array(
0=>5,
1=>10
));
$pod_1 = array("purchase_order_details_id"=>array(
2=>"POD2"
),
"quantity_received"=>array(
2=>20
));
任何人都知道如何做到这一点?任何想法都表示赞赏。感谢
答案 0 :(得分:3)
尝试使用以下代码:
$array = array();
foreach($arr['purchase_order_details_id'] as $key => $val)
{
$array[$val]['purchase_order_details_id'][] = $val;
$array[$val]['quantity_received'][] = $arr['quantity_received'][$key];
}
echo "<pre>";
print_r($array);
echo "</pre>";
extract($array);
echo "<pre>";
print_r($POD1);
echo "</pre>";
echo "<pre>";
print_r($POD2);
echo "</pre>";
答案 1 :(得分:3)
我使用array_intersect在唯一PO的循环中查找PO 然后我使用array_inyersect_key来获取数量 每个唯一的Purchase_order_detali_id只需要一次迭代 这意味着它比循环整个数组具有更好的性能。
编辑:添加提取物以创建两个变量。但如果我是你,我宁愿把它们放在阵列中。
$pods = array_unique($arr["purchase_order_details_id"]);
Foreach($pods as $pod){
$PO = array_intersect($arr["purchase_order_details_id"], [$pod]);
$qt = array_intersect_key($arr["quantity_received"], $PO);
$new[$pod] = ["purchase_order_details_id" => $PO, "quantity_received" => $qt];
}
Var_dump($new);
extract($new);
答案 2 :(得分:1)
foreach ($arr as $key => $val) {
$size = ceil(count($val) / 2);
$arr2 = array_chunk($val, $size, true);
$pod_2[$key] = $arr2[0];
$pod_1[$key] = $arr2[1];
}
var_dump($pod_2);
var_dump($pod_1);