使用 json_decode 格式化数据输出

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 等数据


牧羊人nacy
浏览 98回答 2
2回答

红颜莎娜

你有一个对象数组。您需要连接name和value属性。$array = json_decode($data);foreach ($array as $el) {    echo "{$el->name}-{$el->value},";}

慕的地6264312

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 stringif(json && json.length){&nbsp; &nbsp; for(var j = 0, jLen = json.length; j < jLen; j++){&nbsp; &nbsp; &nbsp; &nbsp; var obIn = Object.values(json[j]);&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; var map = obIn.map(function(el){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return el.trim();&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; var res = map.join('-');&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; arrResult.push(res);&nbsp; &nbsp; &nbsp; &nbsp; //textResult += res;&nbsp; &nbsp; };};console.log(arrResult); // if array//console.log(textResult); // if string控制台结果 [“Agnes-40000”,“John-35000”,“Joyce-50000”,“Peter-45000”]
打开App,查看更多内容
随时随地看视频慕课网APP