0

I have a basic mysql table called basket where I have three values. I am using a foreacg loop to fetch all values and then json_encode to place them inside a json object. I am having some difficulties in getting the right json object format. In the table, there is a field called items and its values are stored in one string separated by commas. How can I take each item and place them inside the original array but in its own array? Below would better explain what I am trying to accomplish

Table

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

current format

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

exptected format

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

1 Answer 1

1

In this particular example, you are wrapping a string in an array, rather than creating an array from a string. Change this:

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

... to this:

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

Obviously you'll need to apply this only where it is relevant to your database results. If this is your only expected result, then this is all you'll need.

I'd also suggest trimming the whitespace off the exploded bits:

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

Docs:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.