[英]Using json_decode to format data output
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 這樣的數據
你有一個對象數組。 您需要連接name
和value
屬性。
$array = json_decode($data);
foreach ($array as $el) {
echo "{$el->name}-{$el->value},";
}
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”]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.