Shayan Khaleghparast Shayan Khaleghparast - 6 months ago 28
JSON Question

save table records in associative array in php

I have an associative array. After I select my records from my table (with two columns: objName,objCost), I want to save them in my array like this:


How should I do this?

This is my code:

$output = '';
$arr = array();
$sql = "SELECT * FROM obj WHERE objName LIKE '%" . $_POST["search"] . "%'";
$result = $db->query($sql) or die(mysql_error());
if ($result->rowCount() != 0) {
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
//here i should insert my rows into my array

$json_arr = json_encode($arr,JSON_UNESCAPED_UNICODE);
echo $json_arr;
} else {
echo 'Data Not Found';


According to your code,

$arr[] = ['objName'=>$row['objName'],'objCost'=>$row['objCost']];

Then you can encode the array and pick up the object on the other side with javascript or php. Which ever suits you


In you Ajax success, get the objects and use the values as you deem fit

success: function (data) {data = JSON.parse(data); 

  for(var i = 0; i < data.length; i++){

see jQuery loop over JSON result from AJAX Success? on how to loop through your results in jquery