【问题标题】:PHP Insert key into a multidimensional arrayPHP将键插入多维数组
【发布时间】:2013-05-30 10:48:44
【问题描述】:

我创建了一个空数组 ($results),其中存储了从 foreach 循环返回的数据。我对在数组中设置的每个 search_tags 关键字执行此操作。一切正常,除了我想将用于从 Instagram api 获取数据的标签 ($tag) 添加到多维数组中。

$search_tags = array(
    "tag1",
    "tag2",
    "tag3"
);

// create empty array
$results=array();

// Get all the data for the tags we are searching for and put it into an array
foreach ($search_tags as $tag) {
    $medias = $instagram->getTagMedia($tag);

    foreach ($medias->data as $media_obj) {
      array_push($results, $media_obj);
      array_push($results, $tag)
    }

}

我尝试使用 array_push 执行此操作,但这会在数组之后添加标签,而不是在数组内部,如下所示。

Array
(
    [0] => stdClass Object
        (
            [attribution] => 
            [location] => 
            [filter] => 
            [created_time] => 
            [link] => 
            [type] => 
            [id] => 
            [user] => 
        )
    [1] => tag1
    [2] => stdClass Object
        (
            [attribution] => 
            [location] => 
            [filter] => 
            [created_time] => 
            [link] => 
            [type] => 
            [id] => 
            [user] => 
        )
    [3] => tag2
    [4] => stdClass Object
        (
            [attribution] => 
            [location] => 
            [filter] => 
            [created_time] => 
            [link] => 
            [type] => 
            [id] => 
            [user] => 
        )
    [5] => tag3
)

有没有办法像这样将标签插入到多维数组中:

Array
(
    [0] => stdClass Object
        (
            [attribution] => 
            [location] => 
            [filter] => 
            [created_time] => 
            [link] => 
            [type] => 
            [id] => 
            [user] => 
            [tag] => tag1
        )
    [2] => stdClass Object
        (
            [attribution] => 
            [location] => 
            [filter] => 
            [created_time] => 
            [link] => 
            [type] => 
            [id] => 
            [user] => 
            [tag] => tag2
        )
    [4] => stdClass Object
        (
            [attribution] => 
            [location] => 
            [filter] => 
            [created_time] => 
            [link] => 
            [type] => 
            [id] => 
            [user] => 
            [tag] => tag3
        )
)

【问题讨论】:

    标签: php arrays object multidimensional-array array-push


    【解决方案1】:

    试试这个:

    // Get all the data for the tags we are searching for and put it into an array
    foreach ($search_tags as $tag) {
        $medias = $instagram->getTagMedia($tag);
    
        foreach ($medias->data as $media_obj) {
          $media_obj->tag = $tag;
          array_push($results, $media_obj);
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2013-10-06
      • 2011-12-12
      • 2021-05-30
      • 2017-07-03
      • 2012-07-21
      • 2019-11-04
      • 2014-01-27
      • 1970-01-01
      相关资源
      最近更新 更多