亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如果 json 中的 id 與 php 相同,則替換值

如果 json 中的 id 與 php 相同,則替換值

PHP
呼如林 2023-05-12 14:31:24
如果 json1 中的 id 與 json2 相同,我嘗試替換 json 值而不是替換 json1 中的名稱,這里是我的 json:$json1 = '[{"categoryId":"10","name":"Technology"},{"categoryId":"10","name":"Blog"},{"categoryId":"11","name":"Programming"}]';$json2 = '[{"categoryId":"10","name":"Tech"}]';我的預期結果是:$json1 = '[{"categoryId":"10","name":"Tech"},{"categoryId":"10","name":"Tech"},{"categoryId":"11","name":"Programming"}]';到目前為止,我使用的是 javascript:json1.forEach(function(json1) {  if (json2.categoryId === json1.categoryId) {    json1.name = json2.name  }});但如何通過 php 語言做到這一點?
查看完整描述

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);


查看完整回答
反對 回復 2023-05-12
?
一只甜甜圈

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.


查看完整回答
反對 回復 2023-05-12
  • 2 回答
  • 0 關注
  • 177 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號