Thursday, 30 August 2018

PHP: target specific JSON array and add POST data correctly?

I have a JSON file that, in essence, is structured like this:

[{
    "name": "James",
    "reviews": [
        {
            "stars": 5,
            "body": "great!"
        },
        {
            "stars": 1,
            "body": "bad!"
        }
    ]
},
{
    "name": "David",
    "reviews": [
        {
            "stars": 4,
            "body": "pretty good!"
        },
        {
            "stars": 2,
            "body": "just ok..."
        }
    ]
}]

Now when positing new review data for David to a PHP script, how do I target David's specific "reviews" and append it?
I have already decoded everything correctly and have access to both the decoded file and post information. I just don't know how to target David's specific reviews in the JSON array... Thank you in advance!
UPDATE - Just to be clear, everything is decoded already, the POST data and the JSON file from the server. I just need to know how to target David's reviews specifically and append it.
UPDATE 2 - Everyone, please also understand that this is in the case that the index is not known. Doing [1] would be awesome, but when someone submits, they won't know what index it is. The loop for the rendering is being done in AngularJS btw, so can't assign anything on the PHP side for the front-end.

PHP >= 5.5.0 needed for array_column or see below for an alternate:
$array[array_search('David', array_column($array, 'name'))]['reviews'][] = array(
    'stars'=>1,'body'=>'meh'
);

Instead of array_column you can use:
array_map(function($v) { return $v['name']; }, $array);

0 comments:

Post a Comment