Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Push data to array in foreach loop [duplicate]

I want to achieve below array format:

{
    "success": true,
    "results": [
      {
        "name"  : "Choice 1",
        "value" : "value1",
        "text"  : "Choice 1"
      },
      {
        "name"  : "Choice 2",
        "value" : "value2",
        "text"  : "Choice 2"
      }
    ]
}

However, I am using PHP and a foreach loop, to return some values from my database:

//Search for clients in our database.
$stmt = $dbh->prepare("SELECT * FROM customers");
$stmt->execute();
$showAll = $stmt->fetchAll();

I then have my first part of the array, and my foreach loop:

$data = array(
    "success" => false,
    "results" => array()
);

foreach ($showAll as $client) {  
               $data_array[] = 
                     array(
                     'name' => $client['name'],
                     'value' => $client['name'],
                     'text' => $client['name']
                );

}

Above only outputs:

[
 {
   "name":"Choice 1",
   "value":"value 1",
   "text":"Choice 1"
 },
 {
   "name":"Choice 2",
   "value":"value2",
   "text":"Choice 2"
 }
]

So it is missing the top part of my original array - but I want to loop through each database results in "results": [ ... ]

like image 605
oliverbj Avatar asked Apr 20 '17 08:04

oliverbj


3 Answers

Try this

$data = array(
  "success" => false,
  "results" => array()
);

foreach ($showAll as $client) {  
  $data['results'][] = array(
    'name' => $client['name'],
    'value' => $client['name'],
    'text' => $client['name']
  );
}

$data['success'] = true; // if you want to update `status` as well
echo json_encode($data);
like image 78
Farooq Ahmed Khan Avatar answered Nov 14 '22 21:11

Farooq Ahmed Khan


After creating $data_array array just add few lines which i have in my post.

Try this code snippet here(with sample input)

ini_set('display_errors', 1);
foreach ($showAll as $client)
{
    $data_array[] = array(
                'name' => $client['name'],
                'value' => $client['name'],
                'text' => $client['name']
    );
}
// add these lines to your code.
$result=array();
$result["success"]=true;
$result["results"]=$data_array;
echo json_encode($result);
like image 33
Sahil Gulati Avatar answered Nov 14 '22 23:11

Sahil Gulati


try this as you have an array inside the $data_array on Key "Results" so you should use "results" as a key also and then try to push data in that array

foreach ($showAll as $client) {  
               $data_array["results"][] = 
                     array(
                     'name' => $client['name'],
                     'value' => $client['name'],
                     'text' => $client['name']
                );

}
like image 24
Badshah Sahib Avatar answered Nov 14 '22 22:11

Badshah Sahib