【问题标题】:how to name keys as push values into php array如何将键命名为将值推送到php数组中
【发布时间】:2015-02-26 14:30:04
【问题描述】:

这可能是一个简单的问题。在 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);

【问题讨论】:

  • 你不能用 array_push() 指定一个键......但为什么不直接做$allourlikes['myNewKey'] = $ourlikes;
  • @Mark Ba​​ker:我想命名 $ourlikes 中的每个键,而不是 $allourlikes。
  • 原理依然适用:array_push() 不允许命名键;但是$ourlikes['myNewKey'] = 'myNewValue'; 会起作用
  • 另一种方法是使用带有命名属性的 stdClass 对象

标签: php instagram-api


【解决方案1】:

你可以的

$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

【讨论】:

  • 就是这样!谢谢!
【解决方案2】:

您可以使用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!
}

【讨论】:

    猜你喜欢
    • 2011-01-08
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    • 2015-02-09
    • 2017-09-25
    • 1970-01-01
    • 2017-03-21
    相关资源
    最近更新 更多