如何判断多维数组中的最后一个键?

时间:2014-04-25 11:00:04

标签: php arrays algorithm sorting foreach

有大量的mutli维数组。

我想通过其中一个值来判断多维数组分组中的最后一个键。

SO,...

TO DO:下面显示的区域#Q。

$i=0;
$j=0;
$limit=10;

$huge_arr = array(
     array("point" => 20
        "os" => "iOS"),
     array("point" => 5
        "os" => "iOS"),
     array("point" => 10
        "os" => "Android"),
     array("point" => 20
        "os" => "Android"),
     array("point" => 7
        "os" => "iOS"),
     array("point" => 3
        "os" => "Android"),
    /*... tons of array..*/
);

foreach($huge_arr as $k => $v)
{

if($v['os'] === "iOS")
{
    $i++;
    if($i % $limit ===0 )
    {
        //Do something By $limit count :#1
    }
    //TO DO
    //#Q:WANT TO DO same thing when there aren't $v['os'] === "iOS" in rest of $array




}
else if($v['os'] === "iOS")
{
    $j++;
    if($j % $limit ===0 )
    {
        //Do something By $limit count :#2
    }
    //TO DO
    //#Q:WANT TO Do same thing when there aren't $v['os'] === "Android" in rest of $array

}

}

使用foreach()语句将$ huge_arr排序为新数组正在增加php内存。

所以我不想这样做。 这种方式是N.G。

foreach($huge_arr as $k => $v)
{
    if($v['os'] === "iOS")
    {
        $ios[] = $v["point"];

    }else if($v['os'] === "Android")
    {
        $ad[] = $v["point"];

    }


}
$ios_count = count($ios);
$ad_count = count($ad);
foreach($ios as $k => $v)
{
    if($k  === $ios_count -1)
    //do something for last value

}

foreach($ad as $k => $v)
{
    if($k  === $ad_count -1)
    //do something for last value

}

有没有人知道聪明的方式......

1 个答案:

答案 0 :(得分:0)

这不需要创建新数组,而只需从数组中获取所需内容 - 假设您只需要最后一个IOS和android密钥。

$ios_key = $ad_key = NULL;  // If one of them is not present key will be NULL

// Reverse the array to put the last key at the top
array_reverse($huge_arr);

foreach($huge_arr as $k => $v)
{
    // Fill key with ios key value if not already set
    if($v['os'] === "iOS" AND $ios_key === NULL) 
    {
        $ios_key = $k;
    }
    // Fill key with first android key value if not already set
    else if($v['os'] === "Android" AND $ad_key === NULL)
    {
        $ad_key = $k;
    }

    // Stop looping when we found both keys
    if($ios_key !== NULL AND $ad_key !== NULL)
        break;
 }

 // Put the array back in original order
 array_reverse($huge_array);

 // Do whatever you want with the array now

对于问题的其他部分do the same thing when there aren't IOS ....

if($i % $limit ===0 )

if($i % $limit === 0 OR $k === $ios_key) // $ios_key should be the last key