如何将键命名为推送值到php数组中

时间:2015-02-26 14:30:05

标签: php instagram-api

这可能是一个简单的问题。在php中,我查询数据库,然后将值推送到数组中,然后将其推入多维数组中。但是,当我将这些值推送到数组中时,如何命名键?我不想要默认的数字键,我想命名键。

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

2 个答案:

答案 0 :(得分:0)

你可以做到

$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

答案 1 :(得分:0)

您可以使用array_merge

if ($likes['username'] == 'ourusername') { 
this    $ourlikes = array_merge(array('url' => $value['images']['standard_resolution']['url']), array('caption' => $value['caption']['text']), array('link' => $value['link']), array('user' => $value['user']['username'])); //this works!
}