为了账号安全,请及时绑定邮箱和手机立即绑定

使用 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条经验 获得超12个赞

你有一个对象数组。您需要连接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 关注
  • 31 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信