简体   繁体   English

将表记录保存在php的关联数组中

[英]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: 从表(两列:objName,objCost)中选择记录后,我想要将它们保存在数组中,如下所示:

array(
      'objName'=>$row['objName'],
      'objCost'=>$row['objCost']
)

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. 然后,您可以对数组进行编码,并使用javascript或php在另一侧拾取对象。 Which ever suits you 哪个适合你

json_encode($arr);

In you Ajax success, get the objects and use the values as you deem fit 在您的Ajax成功中,获取对象并使用您认为合适的值

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

  for(var i = 0; i < data.length; i++){
    alert(data[i].objName);
   }
}

see jQuery loop over JSON result from AJAX Success? 看到jQuery通过AJAX成功对JSON结果进行循环? on how to loop through your results in jquery 关于如何遍历您的结果在jQuery

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM