0

I have a json array (just one row with many attributes) like this :

    $row = '[{"ID":"0","Name":"user","Option":"yes"}]';

I can access to every value with :

    $row->ID; $row->Name; ...

My question is how can I use a loop to found all attributes and their values without using :

$obj = json_decode($row);

2 Answers 2

2

The 2nd argument of json_decode specified that if you give it true, it will return an array instead of an object.

So, if I understand your question correctly, this should be what you're looking for:

$row = '[{"ID":"0","Name":"user","Option":"yes"}]';
foreach (json_decode($row, true) as $key => $value) {
  echo $key . ' = ' . $value . PHP_EOL;
}

Hope this helps :)

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

1 Comment

Oh sorry. It's because they JSON is wrapped in an array. Iterate over this: json_decode($row, true)[0] (PHP 5.4 only in this syntax)
1

Barring the reasoning behind why you'd not just use json_decode... if this is as complicated as your JSON is going to get (just one item in the array), you can piece it apart:

$row = '[{"ID":"0","Name":"user","Option":"yes"}]';

$row = substr($row, 2, strlen($row) - 4); // Removes [{ and }]

$items = explode(',', $row); // Explodes into parts

$final = array();

foreach($items as $item) {
    $parts = explode(':', $item); // Key/value

    $key = substr($parts[0], 1, strlen($parts[0]) - 2); // Remove quotes
    $value = substr($parts[1], 1, strlen($parts[1]) - 2); // Remove quotes

    $final[$key] = $value;
}

var_dump($final);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.