2013-05-30 155 views
-1

我創建了一個空數組($ results),其中存儲了我從foreach循環返回的數據。我爲每個在數組中設置的search_tags關鍵字執行此操作。除了我想添加用於從Instagram API中獲取數據到多維數組的標籤($ tag)之外,它都可以工作。PHP將鍵插入多維數組

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

回答

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

}