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 關注
- 177 瀏覽
添加回答
舉報