如何将每一行放在json索引中?

时间:2016-04-05 09:00:05

标签: php json api rest

对于误导性的标题感到抱歉,无论如何我有这行代码:

$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中。我怎样才能快速,轻松地完成这项工作?

4 个答案:

答案 0 :(得分:1)

您可以使用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);

答案 1 :(得分:0)

这就像说:

$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 [...]

答案 2 :(得分:0)

一个简单的approch可能正在使用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);

答案 3 :(得分:0)

请检查以下脚本。

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