如何在php中将JSON对象转换为普通逗号分隔字符串?

时间:2015-09-12 09:59:00

标签: php arrays json string

var $json = [{name:'abaneel',age:23},
    {name: 'john', age: 32},
    {name: 'Dev' , age:22}
];

如何在php中从这个json对象创建这种类型的字符串,就像这个字符串一样:

$simple string ="abaneel,23,john,32,Dev,22";

2 个答案:

答案 0 :(得分:1)

这里你需要做什么:

$json = '[
  {"name": "abaneel", "age" : 23},
  {"name": "john", "age" : 32},
  {"name": "Dev", "age" : 22}
]';
$implode = array();
$multiple = json_decode($json, true);
foreach($multiple as $single)
    $implode[] = implode(', ', $single);

echo implode(', ', $implode);   //this will output abaneel, 23, john, 32, Dev, 22
/*
    You can see that it will be hard to distinguish that where line(one array is ending);
*/
echo implode(' | ', $implode);  //will output abaneel, 23 | john, 32 | Dev, 22

希望这会有所帮助

答案 1 :(得分:0)

<?php
$json ='[
  {"name": "abaneel", "age" : 23},
  {"name": "john", "age" : 32},
  {"name": "Dev", "age" : 22}
]';

$data=json_decode($json,true);
$your_string="";

foreach($data as $key=>$v){ 
    $your_string.=$data[$key]['name'].",".$data[$key]['age'].",";
}
$your_string= trim($your_string, ",");
echo $your_string;

 ?>