Search code examples
phpinstagram-api

how to name keys as push values into php array


This is probably a simple question. In php I'm querying a database, then pushing values into an array, which I then push into a multidimensional array. But when I'm pushing those values into an array, how do I name the keys? I don't just want the default numbered keys, I want to name the keys.

php:

    $instagram_url = 'https://api.instagram.com/v1/tags/user/media/recent/?client_id=client_id';
  $instagram_json = file_get_contents($instagram_url);
  $instagram_array = json_decode($instagram_json, true);
  $allourlikes = []; 

  if(!empty($instagram_array)){
    foreach($instagram_array['data'] as $key => $value){
       foreach($value['likes']['data'] as $k => $likes){  //find out if *we* liked it
             $ourlikes = [];
            //echo $likes['username']; 
            if ($likes['username'] == 'ourusername') { 
                array_push($ourlikes, 'url' => $value['images']['standard_resolution']['url'], 'caption' => $value['caption']['text'], 'link' => $value['link'], 'user' => $value['user']['username']); //doesn't work
            }
            array_push($allourlikes, $ourlikes);
       }

    }


  }
  echo json_encode($allourlikes);

Solution

  • You can do

    $ourlikes = array();     // or $ourlikes = [];
    if ($likes['username'] == 'ourusername') {
        $ourlikes['url'] = $value['images']['standard_resolution']['url'];
        $ourlikes['caption'] = $value['caption']['text'];
        $ourlikes['link'] = $value['link'];
        $ourlikes['user'] = $value['user']['username']); 
    }
    

    PHP Arrays