Using preg_match_all () in an Array (Notice: Array to string conversion in) php

1

I'm looking for help to resolve the message:

  

Notice: Array to string conversion in

<?php
 $response = '{"data":[{"access_token":"EAAby7f21xKABALPCThZC63i4LZAHZC7MaYbQ0E5gN","id":"515968102105625"},{"access_token":"EAAby7f21xKABAK0zyfHCVNBE0Nn3g1XZCWuXzZA4T","id":"1338263602879836"}],"paging":{"cursors":{"before":"NTE1OTY4MTAyMTA1NjI1","after":"MTMzODI2MzYwMjg3OTgzNgZDZD"}}}';

    if (preg_match_all('#"access_token":[^"]*"([^"]*)"#', $response, $datos)) {
        $mp = $datos[1];
    } else {
        $mp = 'error';
    }
    echo $mp;

    ?>

I'm looking for a way to get the access_token from the variable $ response I hope your help

    
asked by BotXtrem Solutions 17.11.2017 в 06:02
source

1 answer

2

When complying with the condition of the regular expression, the variable $mp will be a array that is why when trying to print with echo it throws the error. It would be more convenient to handle a data type for the two possible options (if .. else)

$response = '{"data":[{"access_token":"EAAby7f21xKABALPCThZC63i4LZAHZC7MaYbQ0E5gN","id":"515968102105625"},{"access_token":"EAAby7f21xKABAK0zyfHCVNBE0Nn3g1XZCWuXzZA4T","id":"1338263602879836"}],"paging":{"cursors":{"before":"NTE1OTY4MTAyMTA1NjI1","after":"MTMzODI2MzYwMjg3OTgzNgZDZD"}}}';

if (preg_match_all('#"access_token":[^"]*"([^"]*)"#', $response, $datos)) {
    $mp = $datos[1];
} else {
    // Tipo array con clave error.
    $mp = array('error' => 'No existen Access Tokens');
}

And to print it would be.

print_r($mp);

If you want String , you could use implode

echo implode(',',$mp);

To avoid regular expressions for this case, you could only have made use of json_decode () to convert the JSON String that has a array and thus be able to directly access (if the second parameter is sent true, the return converts it into an array otherwise in objects)

foreach (json_decode($response)->data as $key => $value) {
    echo $value->access_token."<br>";
}

If you want to separate each value into variables, if you only have 2 values access_token for all cases . otherwise, I would suggest keeping the values in Array

//Convierte en array asociativo con True de segundo parámetro
$newResponse = json_decode($response,TRUE)['data'];
$varone = $newResponse[0]['access_token'];
$vartwo = $newResponse[1]['access_token'];
    
answered by 17.11.2017 / 06:24
source