1

how to add foreach or while loop in json

$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; 
        };

i want get output like this.

{
        "result": "1",
        "message": "Record  founded"
        "data":"name1,name2,name3,name4";
    }
2
  • a while doen't return anything. So you have to fill the var inside (or after) the loop. Commented Jul 30, 2018 at 9:36
  • how to get data without while Commented Jul 30, 2018 at 9:38

2 Answers 2

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;

Anyway, - depending on your situation - I'd recommend to put the whole array $values into $json['data'] if you wanna use that data later, and only implode to string with comma when you actually output the data.

Sign up to request clarification or add additional context in comments.

Comments

1

If you need that exact output you can do like this :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.