1

I have the below JSON I need to loop through in PHP.

    {
 "page": 1,
 "perPage": 3,
 "count": 607,
 "status": "OK",
 "tickers": [
  {
   "ticker": "A",
   "name": "Agilent Technologies Inc.",
   "market": "STOCKS",
   "locale": "US",
   "type": "CS",
   "currency": "USD",
   "active": true,
   "primaryExch": "NYE",
   "updated": "2020-12-15",
   "codes": {
    "cik": "0001090872",
    "figiuid": "EQ0087231700001000",
    "scfigi": "BBG001SCTQY4",
    "cfigi": "BBG000C2V3D6",
    "figi": "BBG000C2V3D6"
   },
   "url": ""
  },
  {
   "ticker": "AA",
   "name": "Alcoa Corporation",
   "market": "STOCKS",
   "locale": "US",
   "type": "CS",
   "currency": "USD",
   "active": true,
   "primaryExch": "NYE",
   "updated": "2020-12-15",
   "codes": {
    "cik": "0001675149",
    "figiuid": "EQ0000000045469815",
    "scfigi": "BBG00B3T3HF1",
    "cfigi": "BBG00B3T3HD3",
    "figi": "BBG00B3T3HD3"
   },
   "url": ""
  },
  {
   "ticker": "WADV",
   "name": "Wireless Advantage Inc Common Stock",
   "market": "STOCKS",
   "locale": "US",
   "type": "CS",
   "currency": "USD",
   "active": true,
   "primaryExch": "GREY",
   "updated": "2020-03-30",
   "codes": {
    "figiuid": "EQ0010295500001000",
    "scfigi": "BBG001S87270",
    "cfigi": "BBG000DKG4K2",
    "figi": "BBG000DKG4K2"
   },
   "url": ""
  }
 ]
}

This is my function to loop through - I simply only need the "ticker" from each of the nested arrays.

public function getTickers()
    {
        $APIKey = "API_KEY";
                
        $tickers_request = 'API_URL';
        $session = curl_init($tickers_request);
        curl_setopt($session, CURLOPT_HEADER, true);
        curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
                
        $response = curl_exec($session);
        curl_close($session);
            
        $json = substr($response, strpos($response, "{"));
            
        $result = json_decode($json, true);
        
        $ticker =[];
        
        foreach($result as $results)  
        {
            foreach ($results['tickers'] as $ticker)
            {
                $ticker['ticker'] = $results['ticker'];
            }
        }
        return $ticker;
        
    }

I receive these two errors in PHP -

A PHP Error was encountered
Severity: Warning

Message: Invalid argument supplied for foreach()

Severity: Notice

Message: Array to string conversion

What's wrong with my function? I'm a seasoned PHP developer but perhaps I am missing something...

Jason Bassett
  • 1,281
  • 8
  • 19
  • `return array_column(json_decode($response, true)['tickers'], 'ticker');` as demonstrated by the first dupe. One line, all done. – mickmackusa Dec 16 '20 at 07:58

2 Answers2

3

Your loop to extract the data isn't accessing the data at the right levels, you only need 1 loop which loops over the tickers array and then adds each ticker element to the new array (not sure what you were hoping the assignment was doing)...

foreach ($result['tickers'] as $res)
{
    $ticker[] = $res['ticker'];
}
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • Is this a unique question? Don't let the hats drag you down. – mickmackusa Dec 16 '20 at 07:38
  • @mickmackusa, IMHO there is a difference between not understanding how to process JSON and where the attempt seems made seems to miss how it works. Just pointing them at a generic solution doesn't always help. – Nigel Ren Dec 16 '20 at 07:41
  • Do I need to post a redundant `array_column()` answer? – mickmackusa Dec 16 '20 at 07:42
  • @mickmackusa, it would probably help if you add some explanation to your duplicate choice as the original question doesn't include `array_column()` at all. So how does a question relating to accessing JSON the same as `array_column()` not working in PHP 7? – Nigel Ren Dec 16 '20 at 07:49
  • "This question already has an answer here:" means the interpretation of "duplicate" is not as strict as it once was. Ultimately, Stack Overflow does not need me to give the same answer for every snowflake question. If an earlier answer contains the solution, I'm closing to avoid redundant content. I could have closed this one with tens of pages (and you know this). – mickmackusa Dec 16 '20 at 07:51
  • @mickmackusa, as you know, I close a lot of duplicates. But I try and balance the difference between helping users and maintaining SO as a strict set of rules. But that conversation is not relevant to this answer. – Nigel Ren Dec 16 '20 at 07:58
3

Your code doesn't make sense. First you don't need the first foreach. All you need is

$result = json_decode($json, true);

$tickers =[];


    foreach ($result['tickers'] as $results)
    {
        $tickers[] = $results['ticker'];
    }
    
return $tickers;

Also your command $ticker['ticker'] doesn't make sense as it would store only 1 variable. I have changed it to $tickers[] = $results['ticker'] to store them in array. The result that way would look like:

array(3) {
  [0]=>
  string(1) "A"
  [1]=>
  string(2) "AA"
  [2]=>
  string(4) "WADV"
}
Mitko Delibaltov
  • 486
  • 1
  • 6
  • 16