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

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

使用 json_decode 格式化數據輸出

使用 json_decode 格式化數據輸出

PHP
牧羊人nacy 2024-01-19 15:10:29
API返回的數據是這樣的格式[{"name":"Agnes ","amount":"40000"},{"name":"John","amount":"35000"},{"name":"Joyce","amount":"50000"},{"name":"Peter","value":"45000"}]我想重新格式化該輸出,使其看起來像這樣: Agnes-40000, John-35000, Joyce-50000, Peter-45000 所以,我寫了這樣的東西,讓 $data 代表上面返回的數據;$new = json_decode($data);          foreach ($new as $key => $jsons) {      foreach($new as $key => $value) {         echo $value;          echo ",";    }}但我得到的輸出如下: Agnes,40000, John,35000, Joyce,50000, Peter,45000 如何編寫 javascript 來顯示 Agnes-40000, John-35000, Joyce-50000, Peter-45000 等數據
查看完整描述

2 回答

?
紅顏莎娜

TA貢獻1842條經驗 獲得超13個贊

你有一個對象數組。您需要連接name和value屬性。


$array = json_decode($data);

foreach ($array as $el) {

    echo "{$el->name}-{$el->value},";

}


查看完整回答
反對 回復 2024-01-19
?
慕的地6264312

TA貢獻1817條經驗 獲得超6個贊

var jsonFromServer = '[{"name":"Agnes ","amount":"40000"},{"name":"John","amount":"35000"},{"name":"Joyce","amount":"50000"},{"name":"Peter","value":"45000"}]';


var json = JSON.parse(jsonFromServer);

var arrResult = []; // if array

//var textResult = ''; // if string


if(json && json.length){

    for(var j = 0, jLen = json.length; j < jLen; j++){

        var obIn = Object.values(json[j]);

        

        var map = obIn.map(function(el){

          return el.trim();

        }); 

        

        var res = map.join('-');

        

        arrResult.push(res);

        //textResult += res;

    };

};


console.log(arrResult); // if array

//console.log(textResult); // if string

控制臺結果 [“Agnes-40000”,“John-35000”,“Joyce-50000”,“Peter-45000”]


查看完整回答
反對 回復 2024-01-19
  • 2 回答
  • 0 關注
  • 149 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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