Search code examples
phparraysjsonarray-mergearray-push

Add to/merge json array


Im building a tool that measures websites for various things.

Im building up an array of info through each check. Ill outline the logic below without loads of code.

var report = [];


 //do a check for an ssl cert, if true...      
    report.push({
      "ssl": "true"
    });

//do a check for analytics tag, if true...
    report.push({
      "analytics": "true"
    });

//Then I run the google insights api and add results to the array...
    report.push(JSON.parse(data));

My result is this...

{
    "ssl": "true"
},
{
    "analytics": "true"
},
{
    "captchaResult": "CAPTCHA_NOT_NEEDED",
    "kind": "pagespeedonline#result",
    "responseCode": 200,

Now I try to read through it

$report = file_get_contents("json.json");
$json = json_decode($report, true);

gives me..

[0] => Array (
    [ssl] => true
    )
[1] => Array (
    [analytics] => true
    )
[3=> Array ( [captchaResult] => CAPTCHA_NOT_NEEDED
[kind] => pagespeedonline#result
[responseCode] => 200)

Unfortunately I cant determine in which order array 1 and 2 will be generated.. so if I try and echo a result like so

echo $json[1]['ssl']

I would get Notice: Undefined index: ssl.

Ideally I would like to get the array like so:

[0] => Array (
    [ssl] => true
    [analytics] => true
    [captchaResult] => CAPTCHA_NOT_NEEDED
    [kind] => pagespeedonline#result
    [responseCode] => 200
)

So I can simply echo out like so, regardless of the order:

  echo $json['ssl'];
  echo $json['analytics'];
  echo $json['captureResult']; etc etc

How can I achieve this?


Solution

  • I think you might also use array_walk_recursive.

    Because the result is a single array, you should make sure not to use duplicate values for the key.

    $result = [];
    array_walk_recursive($arrays, function ($value, $key) use (&$result) {
        $result[$key] = $value;
    });
    
    print_r($result);
    

    Demo

    That would give you:

    Array
    (
        [ssl] => 1
        [analytics] => 1
        [captchaResult] => CAPTCHA_NOT_NEEDED
        [kind] => pagespeedonline#result
        [responseCode] => 200
    )
    

    You could get your value using for example echo $result['ssl'];