第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

如果 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"}]';我的預(yù)期結(jié)果是:$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  }});但如何通過(guò) php 語(yǔ)言做到這一點(diǎn)?
查看完整描述

2 回答

?
富國(guó)滬深

TA貢獻(xiàn)1790條經(jīng)驗(yàn) 獲得超9個(gè)贊

我希望這對(duì)你有幫助


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


查看完整回答
反對(duì) 回復(fù) 2023-05-12
?
一只甜甜圈

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超5個(gè)贊

您的解決方案在 JS 中有效嗎?在我看來(lái),在循環(huán)中,您應(yīng)該與 json2 變量的第一個(gè)條目進(jìn)行比較,因?yàn)檎麄€(gè) json2 是一個(gè)對(duì)象列表,本身沒有屬性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.


查看完整回答
反對(duì) 回復(fù) 2023-05-12
  • 2 回答
  • 0 關(guān)注
  • 364 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)