代码之家  ›  专栏  ›  技术社区  ›  Derek Adair

压缩PHP数组

  •  4
  • Derek Adair  · 技术社区  · 14 年前

    我需要一个看起来像…

    array( 11 => "fistVal", 19 => "secondVal", 120=> "thirdVal", 200 =>"fourthVal");
    

    把它转换成…

    array( 0 => "fistVal", 1 => "secondVal", 2=> "thirdVal", 3 =>"fourthVal");
    

    这就是我想到的-

    function compressArray($array){
        if(count($array){
            $counter = 0;
            $compressedArray = array();
            foreach($array as $cur){
                $compressedArray[$count] = $cur;
                $count++;   
            }
            return $compressedArray;
        } else {
            return false;
        }
    }
    

    我只是好奇在PHP中是否有内置的功能或者简单的技巧来实现这一点。

    3 回复  |  直到 14 年前
        1
  •  11
  •   Anthony Forloney    14 年前

    你可以用 array_values

    直接从链接中获取的示例,

    <?php
    $array = array("size" => "XL", "color" => "gold");
    print_r(array_values($array));
    ?>
    

    输出:

    Array
    (
        [0] => XL
        [1] => gold
    )
    
        2
  •  3
  •   Gumbo    14 年前

    使用 array_values 要获取值数组,请执行以下操作:

    $input = array( 11 => "fistVal", 19 => "secondVal", 120=> "thirdVal", 200 =>"fourthVal");
    $expectedOutput = array( 0 => "fistVal", 1 => "secondVal", 2=> "thirdVal", 3 =>"fourthVal");
    var_dump(array_values($input) === $expectedOutput);  // bool(true)
    
        3
  •  1
  •   hendepher    14 年前

    array_values()可能是最好的选择,但是作为一个有趣的旁注,array_merge和array_splice也将重新索引一个数组。

    $input = array( 11 => "fistVal", 19 => "secondVal", 120=> "thirdVal", 200 =>"fourthVal");
    $reindexed = array_merge($input);
    //OR
    $reindexed = array_splice($input,0); //note: empties $input
    //OR, if you do't want to reassign to a new variable:
    array_splice($input,count($input)); //reindexes $input