Json_encode - 从db获取值并将它们放在数组中

时间:2014-02-24 20:44:59

标签: php

我有一个名为basket的基本mysql表,其中有三个值。我使用foreacg循环来获取所有值,然后使用json_encode将它们放在json对象中。我在获得正确的json对象格式方面遇到了一些困难。在表中,有一个名为items的字段,其值存储在一个以逗号分隔的字符串中。如何将每个项目放在原始数组中但放在自己的数组中?下面将更好地解释我想要实现的目标

+----+------------+---------------------+
| id |    type    |        items        |
+----+------------+---------------------+
| 1  | accesories | watches, sunglasses |
|  2 | jeans      | skinny, slim        |
+----+------------+---------------------+

DB Fetch

$db_select  = $db_con->prepare("SELECT
    b.type,
    b.items
    FROM bakset b
    ");

if (!$db_select) return false;
if (!$db_select->execute()) return false;
$results = $db_select->fetchAll(\PDO::FETCH_ASSOC);
if(!empty($results))
  $responses = array();
  foreach ($results as $value){
    $responses[] = array(
      'type' => $value['type'],
      'items' => array($value['items'])
      );
  }
echo json_encode($responses);

当前格式

[
  {
    type: "accessories",
    items: [
    "watches, sunglasses"
    ]
  }
]

已检测格式

[
  {
    type: "accessories",
    items: [
    "watches", "sunglasses"
    ]
  }
]

1 个答案:

答案 0 :(得分:2)

在此特定示例中,您将字符串包装在数组中,而不是从字符串中创建数组。改变这个:

'items' => array($value['items'])

......对此:

'items' => explode(',', $value['items'])

显然,只有在与数据库结果相关的情况下才需要应用它。如果这是您唯一的预期结果,那么这就是您所需要的。

我还建议修剪爆炸位的空白区域:

'items' => array_map('trim', explode(',', $value['items']))

<强>文档:

相关问题