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.
##
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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 ;
}
|
Copy after login
1 2 | 例如:
$array = array ( array ( 'id' =>1,
|
Copy after login
'name'=>'xiaogou'
Copy after login
array('id'=>2,
Copy after login
'name'=>'xiaomao'
Copy after login
直接return index($array,'id');
Copy after login
The result is
1 | array ('1'=>'xiaogou','2'=>'xiaomao');
|
Copy after login
二、获取数组指定key的value集合
Copy after login
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 ;
}
|
Copy after login
For example:
1 2 | $array = array ( array ('id'=>1,'name'='xiaogou'), array ('id'=>2,'name'=>'xiaomao'));
$array_ids = column( $array ,'id');
|
Copy after login
$array_ids The result is array(0=>1,1=>2);
三、获取数组指定key的值(与上面的集合不同,这个是直接获取值)
Copy after login
1 2 3 4 5 6 | public static function get( array $array , $key , $default ){
if (isset( $array [ $key ])) {
return $array [ $key ];
} else {
return $default ;
}}
|
Copy after login
四、替换多维数组的相同键的值
Copy after login
1 2 3 4 5 6 7 8 9 10 11 | 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 ;
}
|
Copy after login
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!