metokitt
metokitt

Reputation: 53

How to parse this multi-dimensional array properly

I have tried everything I know and I have failed totally to parse this multi dimensional array so that I can get the "symbol" keys and corresponding values of "contractType" , but I can't seem to get it.

The array is generated here: https://fapi.binance.com/fapi/v1/exchangeInfo So I am doing the following:

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, false);
    $data = curl_exec($curl);
    curl_close($curl);

    $results = [];
    foreach ($data['symbols'] as $info) {
        $results[] = $info['symbol'];        
    }
    print_r($results);

I tried a foreach loop, for loop, tried various offsets eg. $data[0]['symbols'].. to $data[9]['symbols'] etc. but can't seem to get the correct array offset.

10000"}],"symbols":[{"symbol":"BTCUSDT","pair":"BTCUSDT","contractType":"PERPETUAL","deliveryDate 

Ty..

Upvotes: 0

Views: 176

Answers (3)

metokitt
metokitt

Reputation: 53

Yes. Thankyou.. (didn't understand answer properly.)

    $url = 'https://fapi.binance.com/fapi/v1/exchangeInfo';
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, false);
    $data = curl_exec($curl);
    curl_close($curl);

    $data = json_decode($data, true);

    $results = [];
    $symbols = $data['symbols'];
    $i = 0;
    foreach ($symbols as $info) {
        $results[$i]['symbol'] = $info['symbol'];
        $results[$i]['contractType'] = $info['contractType'];
        $i++;    
    }
    print_r($results);

Much appreciated, ty..

Upvotes: 0

Simon K
Simon K

Reputation: 1523

It looks like you need to convert the JSON response into an array before you loop over it.

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, false);
    $data = curl_exec($curl);
    curl_close($curl);

    $results = [];
    $data = json_decode($data);
    $i = 0;
    foreach ($data->symbols as $info) {
        $results[$i]['symbol'] = $info->symbol;
        $results[$i]['contractType'] = $info->contractType;
        $i++;    
    }
    print_r($results);

Upvotes: 1

naamhierzo
naamhierzo

Reputation: 430

It doesn't work because the CURL result is in JSON.

You got to convert it to an array before you can loop through it.

$data = json_decode($data, true);

Upvotes: 1

Related Questions