0
[{"id":123456,"name":"Super IT Store","date":"2021-02-08"},{"id":123457,"name":"Duper IT Store","date":"2021-02-08"}]

Good day! How can I split the data above and store it into respective array and eliminate the punctuation?

Example output needed:

id[0] = 123456

id[1] = 123457

name[0] = "Super IT Store"

name[1] = "Duper IT Store"

I have tried to use preg_match_all but it seems weird to extract this kind of data because the actual data could be longer than this a lot.

Stuart Por
  • 23
  • 5

1 Answers1

0

This script will solve your problem

<?php

$json = '[{"id":123456,"name":"Super IT Store","date":"2021-02-08"},{"id":123457,"name":"Duper IT Store","date":"2021-02-08"}]';
$elements = json_decode($json);

$ids   = [];
$names = [];

foreach ($elements as $index => $element) {
    $element       = (array) $element;
    $ids[$index]   = $element['id'];
    $names[$index] = $element['name'];
}

print_r($ids);
print_r($names);

output

Array
(
    [0] => 123456
    [1] => 123457
)
Array
(
    [0] => Super IT Store
    [1] => Duper IT Store
)

First I use json_decode to decode the json and then in the foreach I use this $element = (array) $element; to convert the stdclass object to array and then I can work with it

azibom
  • 1,769
  • 1
  • 7
  • 21