2 回答
TA贡献1790条经验 获得超9个赞
我希望这对你有帮助
// Your json data
$json1 = '[{"categoryId":"10","name":"Technology"},{"categoryId":"11","name":"Blog"},{"categoryId":"12","name":"Programming"}]';
$json2 = '[{"categoryId":"10","name":"Tech"}]';
// Turn json into an array
$array1 = json_decode($json1, true);
$array2 = json_decode($json2, true);
// Loop to json2 as array
foreach ($array2 as $value) {
$categoryId = $value['categoryId'];
// Check if the categoryId exist in array 1 and get the index key
$key = array_search($categoryId, array_column($array1, 'categoryId'));
// Check if the key exist ena check if it has a name to be changed
if (isset($array1[$key]) && isset($array1[$key]['name'])) {
// Set the new name
$array1[$key]['name'] = $value['name'];
}
}
// Turn the array back into json
$json1 = json_encode($array1);
TA贡献1836条经验 获得超5个赞
您的解决方案在 JS 中有效吗?在我看来,在循环中,您应该与 json2 变量的第一个条目进行比较,因为整个 json2 是一个对象列表,本身没有属性name。
在 PHP 中,这可以像这样工作:
$arr1 = json_decode($json1);
$arr2 = json_decode($json2);
$arr2entry = $arr2[0]; # this is what we want to compare against
foreach ($arr1 as &$arr1entry) { #[1]
if ($arr2entry["categoryId"] == $arr1entry["categoryId"]) {
$arr1entry["name"] = $arr2entry["name"];
}
}
#[1] notice the ampersand here, that's a reference assignment,
#it is needed to actually modify the content of the original array.
- 2 回答
- 0 关注
- 137 浏览
添加回答
举报