Home > front end >  How to parse this multi-dimensional array properly
How to parse this multi-dimensional array properly

Time:02-01

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 
  • I'm trying to loop through the "symbols" offset within this main array, and get 1. the "symbol" 2. its corresponding "contractType"

Ty..

CodePudding user response:

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);

CodePudding user response:

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);

CodePudding user response:

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..

  •  Tags:  
  • Related