• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • array_values()

    (PHP 4, PHP 5, PHP 7)

    返回数组中所有的值

    说明

    array_values(array $array): array

    array_values()返回$input数组中所有的值并给其建立数字索引。

    参数

    $array

    数组。

    返回值

    返回含所有值的索引数组。

    范例

    Example #1array_values()例子

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

    以上例程会输出:

    Array
    (
        [0] => XL
        [1] => gold
    )
    

    参见

    • array_keys() 返回数组中部分的或所有的键名
    • array_combine() 创建一个数组,用一个数组的值作为其键名,另一个数组的值作为其值
    Remember, array_values() will ignore your beautiful numeric indexes, it will renumber them according tho the 'foreach' ordering:
    <?php
    $a = array(
     3 => 11,
     1 => 22,
     2 => 33,
    );
    $a[0] = 44;
    print_r( array_values( $a ));
    ==>
    Array(
     [0] => 11
     [1] => 22
     [2] => 33
     [3] => 44
    )
    ?>
    
    This is another way to get value from a multidimensional array, but for versions of php >= 5.3.x
    <?php
    /**
     * Get all values from specific key in a multidimensional array
     *
     * @param $key string
     * @param $arr array
     * @return null|string|array
     */
    function array_value_recursive($key, array $arr){
      $val = array();
      array_walk_recursive($arr, function($v, $k) use($key, &$val){
        if($k == $key) array_push($val, $v);
      });
      return count($val) > 1 ? $val : array_pop($val);
    }
    $arr = array(
      'foo' => 'foo',
      'bar' => array(
        'baz' => 'baz',
        'candy' => 'candy',
        'vegetable' => array(
          'carrot' => 'carrot',
        )
      ),
      'vegetable' => array(
        'carrot' => 'carrot2',
      ),
      'fruits' => 'fruits',
    );
    var_dump(array_value_recursive('carrot', $arr)); // array(2) { [0]=> string(6) "carrot" [1]=> string(7) "carrot2" }
    var_dump(array_value_recursive('apple', $arr)); // null
    var_dump(array_value_recursive('baz', $arr)); // string(3) "baz"
    var_dump(array_value_recursive('candy', $arr)); // string(5) "candy"
    var_dump(array_value_recursive('pear', $arr)); // null
    ?>
    
    Most of the array_flatten functions don't allow preservation of keys. Mine allows preserve, don't preserve, and preserve only strings (default).
    <?
    // recursively reduces deep arrays to single-dimensional arrays
    // $preserve_keys: (0=>never, 1=>strings, 2=>always)
    function array_flatten($array, $preserve_keys = 1, &$newArray = Array()) {
     foreach ($array as $key => $child) {
      if (is_array($child)) {
       $newArray =& array_flatten($child, $preserve_keys, $newArray);
      } elseif ($preserve_keys + is_string($key) > 1) {
       $newArray[$key] = $child;
      } else {
       $newArray[] = $child;
      }
     }
     return $newArray;
    }
    // Tests
    $array = Array(
     'A' => Array(
      1 => 'foo',
      2 => Array(
       'a' => 'bar'
      )
     ),
     'B' => 'baz'
    );
    echo 'var_dump($array);'."\n";
    var_dump($array);
    echo 'var_dump(array_flatten($array, 0));'."\n";
    var_dump(array_flatten($array, 0));
    echo 'var_dump(array_flatten($array, 1));'."\n";
    var_dump(array_flatten($array, 1));
    echo 'var_dump(array_flatten($array, 2));'."\n";
    var_dump(array_flatten($array, 2));
    ?>
    
    Just a warning that re-indexing an array by array_values() may cause you to reach the memory limit unexpectly.
    For example, if your PHP momory_limits is 8MB,
     and says there's a BIG array $bigArray which allocate 5MB of memory.
    Doing this will cause PHP exceeds the momory limits:
    <?php
     $bigArray = array_values( $bigArray );
    ?>
    It's because array_values() does not re-index $bigArray directly,
    it just re-index it into another array, and assign to itself later.
    <?php 
    /**
      flatten an arbitrarily deep multidimensional array 
      into a list of its scalar values
      (may be inefficient for large structures)
      (will infinite recurse on self-referential structures)
      (could be extended to handle objects)
    */
    function array_values_recursive($ary)
    {
      $lst = array();
      foreach( array_keys($ary) as $k ){
       $v = $ary[$k];
       if (is_scalar($v)) {
         $lst[] = $v;
       } elseif (is_array($v)) {
         $lst = array_merge( $lst,
          array_values_recursive($v)
         );
       }
      }
      return $lst;
    }
    ?>
    code till dawn! -mark meves!
    If you are looking for a way to count the total number of times a specific value appears in array, use this function:
    <?php
    function array_value_count ($match, $array)
    {
      $count = 0;
      
      foreach ($array as $key => $value)
      {
        if ($value == $match)
        {
          $count++;
        }
      }
      
      return $count;
    }
    ?>
    This should really be a native function of PHP.
    <?php
    $array = array(
      'fruit1' => 'apple',
      'fruit2' => 'orange',
      'fruit3' => ' ',
      'fruit4' => ' ',
      'fruit5' => 'apple');
      for ($i = 0; $i < count($array); $i++) {
      $key=key($array);
      $val=$array[$key];
      if ($val<> ' ') {
        echo $key ." = ". $val ." <br> ";
        }
       next($array);
      }
    /*
    fruit1 = apple
    fruit2 = orange
    fruit5 = apple
    */
    ?>
    
    I needed a function that recursively went into each level of the array to order (only the indexed) arrays... and NOT flatten the whole thing.
    Solution:
    <?php
    function array_values_recursive($arr){
        $arr = array_values($arr);
        foreach($arr as $key => $val)
          if(array_values($val) === $val)
            $arr[$key] = array_values_recursive($val);
        
        return $arr;
    }
    ?>
    
    <?php
    /**********************************************
     *
     *  PURPOSE: Flatten a deep multidimensional array into a list of its
     *  scalar values
     *
     *  array array_values_recursive (array array)
     *
     *  WARNING: Array keys will be lost
     *
     *********************************************/
    function array_values_recursive($array)
    {
      $arrayValues = array();
      foreach ($array as $value)
      {
        if (is_scalar($value) OR is_resource($value))
        {
           $arrayValues[] = $value;
        }
        elseif (is_array($value))
        {
           $arrayValues = array_merge($arrayValues, array_values_recursive($value));
        }
      }
      return $arrayValues;
    }
    ?>
    This function is an improved and faster version of the one posted by <27-Apr-2004 09:47>
    extract all values from a multi dimesnsional array or a nexted json object
    function array_keys_multi($array,&$vals)
    {
      foreach ($array as $key => $value) {
        if (is_array($value)) {
            
          array_keys_multi($value,$vals);
        
        }else{
          
          $vals[] = $value; 
        }
      }
     
      return $vals;
    }
    Non-recursive simplest array_flatten.
    <?php
    function array_flatten($arr) {
      $arr = array_values($arr);
      while (list($k,$v)=each($arr)) {
        if (is_array($v)) {
          array_splice($arr,$k,1,$v);
          next($arr);
        }
      }
      return $arr;
    }
    ?>
    
    same array_flatten function, compressed and preserving keys.
    function array_flatten($a,$f=array()){
     if(!$a||!is_array($a))return '';
     foreach($a as $k=>$v){
      if(is_array($v))$f=array_flatten($v,$f);
      else $f[$k]=$v;
     }
     return $f;
    }
    /**
    * Return the new array from the offset index
    */
    function array_values_from($array, $offset_index = 0) {
      if (!is_array($array))
        return null;
      $index = (int)$offset_index;
      foreach($array as $i => $value)
        $array_return[$index++] = $value;
      return $array_return;
    }
    A modification of wellandpower at hotmail.com's function to perform array_values recursively. This version will only re-index numeric keys, leaving associative array indexes alone.
    <?php
    function array_values_recursive($array) {
      $temp = array();
      foreach ($array as $key => $value) {
        if (is_numeric($key)) {
          $temp[] = is_array($value) ? array_values_recursive($value) : $value;
        } else {
          $temp[$key] = is_array($value) ? array_values_recursive($value) : $value;
        }
      }
      return $temp;
    }
    ?>
    
    <?php
    $array = array("size" => "XL", "color" => "gold","x" => " ","y" => "gold","z" => "");
    print_r(array_values($array));
    ?> 
    wil result:
    Array ( [0] => XL [1] => gold [2] => [3] => gold [4] => )
    Please note that 'wellandpower at hotmail.com's recursive merge doesn't work. Here's the fixed version:
    <?php
    function array_values_recursive($array) {
      $flat = array();
      foreach ($array as $value) {
          if (is_array($value)) $flat = array_merge($flat, array_values_recursive($value));
          else $flat[] = $value;
      }
      return $flat;
    }
    ?>
    
    A comment on array_merge mentioned that array_splice is faster than array_merge for inserting values. This may be the case, but if your goal is instead to reindex a numeric array, array_values() is the function of choice. Performing the following functions in a 100,000-iteration loop gave me the following times: ($b is a 3-element array)
    array_splice($b, count($b)) => 0.410652
    $b = array_splice($b, 0) => 0.272513
    array_splice($b, 3) => 0.26529
    $b = array_merge($b) => 0.233582
    $b = array_values($b) => 0.151298
    The function here flatterns an entire array and was not the behaviour I expected from a function of this name.
    I expected the function to flattern every sub array so that all the values were aligned and it would return an array with the same dimensions as the imput array, but as per array_values() adjusting the keys rater than removing them.
    In order to do this, you will want this function:
    function array_values_recursive($array) {
      $temp = array();
      foreach ($array as $value) {
          if(is_array($value)) { $temp[] = array_values_recursive($value); }
          else { $temp[] = $value; }
      }
      return $temp;
    }
    Hopefully this will assist.
    Remember, that the following way of fetching data from a mySql-Table will do exactly the thing as carl described before: An array, which data may be accessed both by numerical and DB-ID-based Indexes:
    <?php
    $row = mysql_fetch_array($db_result, $db_link);
    ?>
    Hope I haven't misunderstood anything here.. :)
    Indeed you can, and that's what's so great about it. I have, for instance, a function that returns the results of a database query as an array. I want to keep the order that the entries were returned in, but at the same time I want to be able to access them _either_ by the position _or_ by some other index (such as some sort of ID in the database, gotten from elsewhere). In this case, I can make the function return an array from id to [array of values], and by a simple call to array_values() this is transformed into an array indexed from 0 to count() 1. Useful.
    Note that in a multidimensional array, each element may be identified by a _sequence_ of keys, i.e. the keys that lead towards that element. Thus "preserving keys" may have different interpretations. Ivan's function for example creates a two-dimensional array preserving the last two keys. Other functions below create a one-dimensional array preserving the last key. For completeness, I will add a function that merges the key sequence by a given separator and a function that preserves the last n keys, where n is arbitrary.
    <?php
    /*
     * Flattening a multi-dimensional array into a 
     * single-dimensional one. The resulting keys are a
     * string-separated list of the original keys:
     *
     * a[x][y][z] becomes a[implode(sep, array(x,y,z))]
     */
    function array_flatten_sep($sep, $array) {
     $result = array();
     $stack = array();
     array_push($stack, array("", $array));
     while (count($stack) > 0) {
      list($prefix, $array) = array_pop($stack);
      foreach ($array as $key => $value) {
       $new_key = $prefix . strval($key);
       if (is_array($value))
        array_push($stack, array($new_key . $sep, $value));
       else
        $result[$new_key] = $value
      }
     }
     return $result;
    }
    /*
     * Flattening a multi-dimensional array into an 
     * n-dimensional one. The last n keys of each element are 
     * preserved. If this results in ambiguities, results are 
     * undefined.
     *
     * a[x_1][x_2]...[x_m] becomes a[x_{m-n+1}]...[x_m]
     */
    function array_flatten_n($array, $n) {
     $result = array();
     $stack = array();
     array_push($stack, array(array(), $array));
     while (count($stack) > 0) {
      list($prefix, $array) = array_pop($stack);
      foreach ($array as $key => $value) {
       if (is_array($value)) {
        $new_prefix = array_values($prefix);
        array_push($new_prefix, $key);
        if (count($new_prefix) >= n)
         array_shift($new_prefix);
        array_push($stack, array($new_prefix, $value));
       } else {
        $array = $result;
        foreach ($prefix as $pkey) {
          if (!is_array($array[$pkey]))
           $array[$pkey] = array();
          $array = $array[$pkey];
        }
        $array[$key] = $value;
       }
      }
     }
     return $result;
    }
    ?>
    
    @Yassin Ezbakhe <yassin88 at gmail dot com>
    When we have to flatten multidimensional array of strings or numbers this method could be much faster.
    Inconvenience of this method is, that its speed depends on size of strings/numbers, which array contains - bigger strings, lower efficiency.
    Conclusion: Use this method for small amount of data in arrays (less than 500B per element in my case) which have many dimensions, in other case, use Yassin Ezbakhe method.
    <?php
    function md_implode($array, $glue = '')
    {
      if (is_array ($array))
      {
        $output = '';
        foreach ($array as $v)
        {
          $output .= md_implode($v, $glue);
        }
        return $output;
      }
      else
      {
        return $array.$glue;
      }
    }
    function md_array_flatten($md_array)
    {
      $flat_array = explode ('#|#',md_implode($md_array,'#|#')); // "#|#" is a sample delimiter
      array_pop($flat_array); // to remove last empty element
      return $flat_array;
    }
    //Usage:
    $flat_array = md_array_flatten($some_md_array)
    ?>
    
    Good function, if you want to acces associative array element by position:
    <?php
    $array = array('fruit'=>'apple', 'juice'=>'orange', 'color'=>'lime');
    $array = array_values($array);
    echo $array[2];
    ?>
    
    <?php
    /**
     * Flattens an array, or returns FALSE on fail.
     */
    function array_flatten($array) {
     if (!is_array($array)) {
      return FALSE;
     }
     $result = array();
     foreach ($array as $key => $value) {
      if (is_array($value)) {
       $result = array_merge($result, array_flatten($value));
      }
      else {
       $result[$key] = $value;
      }
     }
     return $result;
    }
    ?>
    
    In case you want to replace all keys in multiarrays by integers starting at 0, the following function might help.
    <?php
    function numerieren($array)
    {
    $array_v = array_values($array);
    $count_v = count($array_v);
    for ($i=0; $i<$count_v; $i++)
     if (is_array($array_v[$i]))
      $array_v[$i] = numerieren($array_v[$i]);
    return $array_v;
    }
    ?>