![](/img/trans.png)
[英]How to get multiple rows of JSON data and put it into some sort of Array?
[英]How to put each rows in json index?
對不起,誤導性的標題,無論如何我有這行代碼:
$results = $this->db->select("SELECT * FROM user");
if(count($results) > 0)
{
return '{"user": ' . json_encode($results) . '}';
}
return http_response_code(204);
上面的代碼允許我獲取用戶列表,實際上我得到了這個結果:
{
"user": [
{
"id": "R89d",
"description": "admin",
"created": "2016-03-20 20:45:09",
"lastUpdate": "2016-03-20 20:45:09"
},
{
"id": "RB01",
"description": "normal",
"created": null,
"lastUpdate": "2016-03-22 10:54:48"
},
{
"id": "RT40",
"description": "tester",
"created": null,
"lastUpdate": null
}
]
}
但我需要得到這個結果:
{
"user": [
{
"details":{
"id": "R89d",
"description": "admin",
"created": "2016-03-20 20:45:09",
"lastUpdate": "2016-03-20 20:45:09"
}
},
{
"details":{
"id": "RB01",
"description": "normal",
"created": null,
"lastUpdate": "2016-03-22 10:54:48"
}
},
{
"details":{
"id": "RT40",
"description": "tester",
"created": null,
"lastUpdate": null
}
}
]
}
您如何在索引details
查看每個用戶。 我怎樣才能快速輕松地做到這一點?
您可以使用array_map
將數據包裝在詳細信息對象中。 像這樣:
<?php
$results = $this->db->select("SELECT * FROM user");
if(count($results) > 0)
{
$results = array_map(function($u) { return ['details' => $u]; }, $results);
return '{"user": ' . json_encode($results) . '}';
}
return http_response_code(204);
這就像在說:
$makes = array( 'car' => 'ford', 'car' => 'citron', 'car' => $anotherCar );
您無法獲得$makes['car']
。
因此,您可以存儲一個臨時數組以使用並將詳細信息作為數組附加,如下所示:
$temp = array();
if(count($results) > 0)
{
foreach ($results as $v)
{
array_push($temp, $v);
}
return '{"user": ' . json_encode($temp) . '}';
}
但是details
將替換為0,1,2 [...]
。
一個簡單的方法可能是使用 foreach ...
$results = $this->db->select("SELECT * FROM user");
if(count($results) > 0)
{
$resultnew = array();
foreach($results as $result)
{
$resultnew['details'][] = $result;
}
return '{"user": ' . json_encode($resultnew) . '}';
}
return http_response_code(204);
請檢查以下腳本。
$results = $this->db->select("SELECT * FROM user");
$a = json_decode($results,true);
foreach ($a as $key => $value) {
$b[]['details'] = $value;
}
$new_result = json_encode($b);
if(count($results) > 0)
{
return '{"user": ' . $new_result . '}';
}
return http_response_code(204);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.