获取数组中的第n个键/值?

时间:2013-01-06 23:23:38

标签: php arrays multidimensional-array

有一个像这样的数组:

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
        )

)

我如何从这个foreach中获取[2]并将其插入到此:

foreach($fotoSuggSizes as $fotoSuggSize100)
    {

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

    }

4 个答案:

答案 0 :(得分:1)

您可以使用array_splice在exisitng数组中的特定偏移处插入另一个数组:

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

但是,如果您正在寻找的话,我不能完全确定您的问题。

另一种方式是:

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

答案 1 :(得分:1)

另一种方式是:

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

答案 2 :(得分:1)

原始数组是否为$fotoSuggSize100

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

答案 3 :(得分:1)

也许我错过了这一点,但是:

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

或者,如果由于某种原因您特别想使用foreach()方法:

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