Search code examples
phparraysjsonjson-deserialization

Getting value from string by index


I have a string of data formatted like so:

[{"pr_a_w":"10","pr_a_we":"10","pr_c_w":"10","pr_c_we":"10"},{"pr_a_w":"20","pr_a_we":"20","pr_c_w":"20","pr_c_we":"20"},{"pr_a_w":"111","pr_a_we":"11","pr_c_w":"111","pr_c_we":"111"}]

The string doesn't have any index/numbers like a regular array would and I'm finding it difficult to extract individual values e.g. with a regular array I could use:

$string[0]["pr_a_w"] 

To get the first instance of "pr_a_w" and I could use:

$string[1]["pr_a_w"] 

To get the second instance etc.

Is it possible to get single values from this string based on their number?


Solution

  • What you have there is valid JSON (serialized array of objects), so you could use json_decode to translate the serialized data into a native PHP array:

    $array = json_decode('[{"pr_a_w":"10","pr_a_we":"10","pr_c_w":"10","pr_c_we":"10"},{"pr_a_w":"20","pr_a_we":"20","pr_c_w":"20","pr_c_we":"20"},{"pr_a_w":"111","pr_a_we":"11","pr_c_w":"111","pr_c_we":"111"}]',true);
    

    $array will then allow you to do exactly what you stated you'd like to do above.

    $array[0]["pr_a_w"]; // will give you 10
    $array[1]["pr_a_w"]; // will give you 10