根据条件 PHP 在关联数组中插入数据
insert data in associative array based on condition PHP
我有两个数组:
$sizes
和 $percentages
$sizes
看起来像这样:
"sizes":{"0":{"size_id":5,"it":"50","us":"32"},"1":{"size_id":4,"it":"48","us":"30"}},
和$percentages
像这样:
"percentages":[{"5":"70"},{"4":"30"}]
我想根据百分比的 $key 值将数据从 $sizes 数组中插入到 "size_id" in $sizes 并以此结尾:
"sizes_with_percentage":{"0":{"size_id":5,"percentage":70,it":"50","us":"32"},"1":{"size_id":4,"percentage":30"it":"48","us":"30"}},
我尝试了一些嵌套循环,但没有找到合适的方法,array_push_assoc returns "call to undefined bla bla error".
假设您首先使用 json_decode
在这里创建了真正的数组:
$sizes = json_decode('{"0":{"size_id":5,"it":"50","us":"32"},"1":{"size_id":4,"it":"48","us":"30"}}', true);
$percentages = json_decode('[{"5":"70"},{"4":"30"}]', true);
您可以非常简单地构建一个 $final
数组。
首先循环大小,将它们添加到 $final
,使用 size_id
作为数组键。这将使接下来的步骤变得更加容易。
foreach($sizes AS $size) {
$final[$size['size_id']] = $size;
}
现在遍历百分比,使用键找到正确的 $final
条目,并添加百分比元素。
foreach($percentages AS $percentage) {
$final[key($percentage)]['percentage'] = current($percentage);
}
大功告成!如果您不希望 $final
数组仍然由 size_id
键入,您可以删除它:
$final = array_values($final);
当然,如果您希望输出为 json:
$finalJson = json_encode($final);
我有两个数组:
$sizes
和 $percentages
$sizes
看起来像这样:
"sizes":{"0":{"size_id":5,"it":"50","us":"32"},"1":{"size_id":4,"it":"48","us":"30"}},
和$percentages
像这样:
"percentages":[{"5":"70"},{"4":"30"}]
我想根据百分比的 $key 值将数据从 $sizes 数组中插入到 "size_id" in $sizes 并以此结尾:
"sizes_with_percentage":{"0":{"size_id":5,"percentage":70,it":"50","us":"32"},"1":{"size_id":4,"percentage":30"it":"48","us":"30"}},
我尝试了一些嵌套循环,但没有找到合适的方法,array_push_assoc returns "call to undefined bla bla error".
假设您首先使用 json_decode
在这里创建了真正的数组:
$sizes = json_decode('{"0":{"size_id":5,"it":"50","us":"32"},"1":{"size_id":4,"it":"48","us":"30"}}', true);
$percentages = json_decode('[{"5":"70"},{"4":"30"}]', true);
您可以非常简单地构建一个 $final
数组。
首先循环大小,将它们添加到 $final
,使用 size_id
作为数组键。这将使接下来的步骤变得更加容易。
foreach($sizes AS $size) {
$final[$size['size_id']] = $size;
}
现在遍历百分比,使用键找到正确的 $final
条目,并添加百分比元素。
foreach($percentages AS $percentage) {
$final[key($percentage)]['percentage'] = current($percentage);
}
大功告成!如果您不希望 $final
数组仍然由 size_id
键入,您可以删除它:
$final = array_values($final);
当然,如果您希望输出为 json:
$finalJson = json_encode($final);