如何在json数组中添加while或foreach循环?

时间:2018-07-30 09:32:34

标签: php json

如何在json中添加foreach或while循环

$p = $db->query("select * from person");
        $json['result'] = '1';
        $json['message'] = 'Record founded';
        $json['data'] = while($row = $p->fetch_array()){
        $user_result = $row['f_name'].',';
        echo $user_result; 
        };

我想要这样的输出。

{
        "result": "1",
        "message": "Record  founded"
        "data":"name1,name2,name3,name4";
    }

2 个答案:

答案 0 :(得分:2)

$p = $db->query("select * from person");
$json['result'] = '1';
$json['message'] = 'Record founded';

$values = []; // initialize an array
while($row = $p->fetch_array()){
    //extract($rp); // don't know what this is for here

    // fill the array
    $values[] = $row['f_name'];
}
// implode it to a string with commas in between
$user_result = implode(",", $values);

$json['data'] = $user_result;

无论如何,-根据您的情况-如果以后要使用该数据,建议将整个数组$values放入$json['data']中,并且仅在实际输出时才内含逗号数据。

答案 1 :(得分:1)

如果您需要确切的输出,可以这样:

 $string = "";
 while($row = $p->fetch_array()){
     $string .= $row['f_name'] . ',';
 }
 $string = rtrim(",", $string);
 $json['data'] = $string;