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');
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; }
$array = array(array('id'=>1,'name'='xiaogou'),array('id'=>2,'name'=>'xiaomao')); $array_ids = column($array,'id');
三、获取数组指定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!