以輸出如下所示的方式轉換以下陣列的最佳方法是什么。
初始陣列
array:2 [▼
0 => array:4 [▼
"group" => "1"
4 => "19"
6 => "27"
8 => "160"
]
1 => array:4 [▼
"group" => "2"
4 => "20"
6 => "28"
8 => "200"
]
]
所需的陣列:
array:6 [▼
0 => array:3 [▼
"group" => "1"
"es_variation_set_id" => "4" << this is key form the initial array
"es_variation_id" => "19" << this is value form the initial array
]
1 => array:3 [▼
"group" => "1"
"es_variation_set_id" => "6" << this is key form the initial array
"es_variation_id" => "28" << this is value form the initial array
]
2 => array:3 [▼
"group" => "1"
"es_variation_set_id" => "8" << this is key form the initial array
"es_variation_id" => "160" << this is value form the initial array
]
3 => array:3 [▼
"group" => "2"
"es_variation_set_id" => "4" << this is key form the initial array
"es_variation_id" => "20" << this is value form the initial array
]
4 => array:3 [▼
"group" => "2"
"es_variation_set_id" => "6" << this is key form the initial array
"es_variation_id" => "28" << this is value form the initial array
]
5 => array:3 [▼
"group" => "1"
"es_variation_set_id" => "8" << this is key form the initial array
"es_variation_id" => "200" << this is value form the initial array
]
]
這是我的 foreach
foreach ($request->only('product_variations')['product_variations'] as $variation_value)
{
if($variation_value['group'] != 0){
dd($variation_value);
}
}
請建議解決此問題的最佳方法
提前致謝
uj5u.com熱心網友回復:
您可以使用嵌套foreach回圈解決此問題,該回圈group在每次運行之前提取該值。
$output = [];
foreach ($input as $subArray) {
$group = $subArray['group'];
unset($subArray['group']);
foreach ($subArray as $setId => $variationId) {
$output[] = [
'group' => $group,
'es_variation_set_id' => $setId,
'es_variation_id' => $variationId,
];
}
}
演示在這里:https : //3v4l.org/KLf8Y
uj5u.com熱心網友回復:
你快到了。您只需要在 if 條件中添加另一個 foreach 來單獨添加組、鍵和值對。
<?php
$res = [];
foreach ($request->only('product_variations')['product_variations'] as $variation_value){
if($variation_value['group'] != 0){
foreach($variation_value as $k => $v){
if($k == 'group') continue;
$res[] = [
'group' => $variation_value['group'],
'es_variation_set_id' => $k,
'es_variation_id' => $v
];
}
}
}
print_r($res);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/365237.html
上一篇:使用AJAX將PHPPOST結果加載到Modal中?
下一篇:不用回圈替換陣列中的字串
