Home  >  Article  >  Backend Development  >  How to deal with PHP array issues

How to deal with PHP array issues

零到壹度
零到壹度Original
2018-04-11 11:17:401574browse


The content of this article is about how to deal with PHP array problems. It has a certain reference value. Friends in need can refer to it

1. There are two sets of data in an array. The value of the specified key is used as the new index, and the value of the other key is used as the value of the new index.
##

public static function index(array $array, $name){  
  $indexedArray = array();    
  
  if (empty($array)) {    
      return $indexedArray;    
  }    
  
  foreach ($array as $item) {    
      if (isset($item[$name])) {      
            $indexedArray[$item[$name]] = $item;            
            continue;        
           }    
       }    
       
       return $indexedArray;
  }
例如:
$array = array(array('id'=>1,
           'name'=>'xiaogou'
          ),
          array('id'=>2,
           'name'=>'xiaomao'
        )
直接return index($array,'id');
The result is

array('1'=>'xiaogou','2'=>'xiaomao');

二、获取数组指定key的value集合
public static function column(array $array, $columnName){  
  if (empty($array)) {    
      return array();    
  }    
  
  $column = array();    
  
  foreach ($array as $item) {    
      if (isset($item[$columnName])) {       
           $column[] = $item[$columnName];        
      }    
 }    
      return $column;
 }
For example:

$array = array(array('id'=>1,'name'='xiaogou'),array('id'=>2,'name'=>'xiaomao'));
$array_ids = column($array,'id');

$array_ids The result is array(0=>1,1=>2);

三、获取数组指定key的值(与上面的集合不同,这个是直接获取值)
public static function get(array $array, $key, $default){  
  if (isset($array[$key])) {     
     return $array[$key];    
  } else {     
     return $default;    
  }}
四、替换多维数组的相同键的值
public static function rename(array $array, array $map){  
  $keys = array_keys($map);    
  
  foreach ($array as $key => $value) {    
      if (in_array($key, $keys)) {       
           $array[$map[$key]] = $value;            
           unset($array[$key]);        
       }    
  }    
       return $array;
  }

The above is the detailed content of How to deal with PHP array issues. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn