2013-01-06 76 views
-1

有一個數組,像這樣:獲取數組中的第n個鍵/值?

Array 
(
    [0] => stdClass Object 
     (
      [url] => https://is0.Z0V.jpg 
      [width] => 370 
      [height] => 370 
     ) 

    [1] => stdClass Object 
     (
      [url] => https://is1.et/derived_pi0V_300x300.jpg 
      [width] => 300 
      [height] => 300 
     ) 

    [2] => stdClass Object 
     (
      [url] => https://is1.n100x100.jpg 
      [width] => 100 
      [height] => 100 
     ) 

    [3] => stdClass Object 
     (
      [url] => https://is1.t/dZ0V_36x36.jpg 
      [width] => 36 
      [height] => 36 
     ) 

) 

如何我只得到了[2]這的foreach並將其插入這樣的:

foreach($fotoSuggSizes as $fotoSuggSize100) 
    { 

     $image_urlSugg100[] = array("urlx100"=>$fotoSuggSize100->url); 

    } 
+0

插入或覆蓋?什麼是http://php.net/array_splice? – hakre

+0

ehm ...你的意思是'$ fotoSuggSizes [2] - > url' ?! – KingCrunch

+0

對不起,只是爲了得到! – hellomello

回答

1

您可以在特定於exisitng偏移插入數組另一個數組使用array_splice

$insert = array("urlx100"=>$fotoSuggSize100->url); 
array_splice($fotoSuggSizes, 2, 0, array($insert)); 

但是我不能完全肯定從你的問題,如果這是你在找什麼。

倒過來應該是:

$image_urlSugg100[] = array("urlx100" => $fotoSuggSizes[2]->url); 
1

另一種方式是以下幾點:

foreach($fotoSuggSizes as $n => $fotoSuggSize100) 
{ 
    if ($n != 2) continue; 
    $image_urlSugg100[] = array("urlx100"=>$fotoSuggSize100->url); 
} 
1

是原始數組稱爲$fotoSuggSize100

$image_urlSugg100[] = array("urlx100"=>$fotoSuggSize100[2]->url); 
1

也許我錯過了點,但是:

$image_urlSugg100[] = array("urlx100"=>$fotoSuggSizes[2]->url); 

或者,如果由於某種原因,你特別想使用的foreach()方法:

foreach ($fotoSuggSizes as $k => $v) 
{ 
    if ($k == 2) 
    { 
     $image_urlSugg100[] = array("urlx100"=>$v->url); 
    } 
}