0

I have a file with content similar to this:

[{"color":1,"blocks":[[{"id":64}]]},{"color":1,"blocks":[[{"id":64},{"id":64}],[{"id":1}]]},{"color":2,"blocks":[[{"id":64},{"id":64}],[{"id":1}]]}]

For example the file above has 3 objects with elements: color and blocks. I am searching for an easy way with PHP to output only one object of the file. (remove outer []-brackets and split first level {}-brackets into different elements of an array or different strings or something)

The result should be for object1

{"color":1,"blocks":[[{"id":64}]]} 

or for object2

{"color":1,"blocks":[[{"id":64},{"id":64}],[{"id":1}]]}

How to say PHP take the string and split it for each {"color" it can find into parts or by using the first level {}-brackets?

at the moment I am using $config=json_decode($file,true); and my code is like echo '{"color":'.$config[2]["color"].'"blocks" ... but thats crazy the object has too many elements i need a way like echo $config[2] that outputs {"color":2,"blocks":[[{"id":64},{"id":64}],[{"id":1}]]}

I tried to read the file as string and use explode but "}," or "color" as delimiter does not work and I can't find a valid delimiter.

2 Answers 2

3

You're going about it wrong. You don't output json, you extract the sub-array/object and then re-encode that. e.g.

$foo = json_decode($your_json);
$temp = $foo['bar'][1]['baz']; // deep sub-data
echo json_encode($temp);

No substring operations/mangling required. Just decode, extract, re-encode extracted portion.

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

Comments

0

Decode then encode:

$str = '[{"color":1,"blocks":[[{"id":64}]]},{"color":1,"blocks":[[{"id":64},{"id":64}],[{"id":1}]]},{"color":2,"blocks":[[{"id":64},{"id":64}],[{"id":1}]]}]';
$config = json_decode($str, true);
$json = json_encode($config[2]);
print $json;

This will print what you want.

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.