demo示例:
1 $data = array( 2 ‘0‘ => array(‘id‘ => 10, ‘username‘ => ‘陈一‘), 3 ‘1‘ => array(‘id‘ => 11, ‘username‘ => ‘洪二‘), 4 ‘2‘ => array(‘id‘ => 12, ‘username‘ => ‘张三‘), 5 ‘3‘ => array(‘id‘ => 13, ‘username‘ => ‘李四‘) 6 );
方法一: foreach循环方法实现
1 foreach ($data as $key=>$value) { 2 $idData[] = $value[‘id‘]; 3 $usernameData[] = $value[‘username‘]; 4 } 5 6 var_dump($idData);//array(4) { [0]=> int(10) [1]=> int(11) [2]=> int(12) [3]=> int(13) } 7 var_dump($usernameData);//array(4) { [0]=> string(6) "陈一" [1]=> string(6) "洪二" [2]=> string(6) "张三" [3]=> string(6) "李四" }
方法二: array_map函数方法 函数将用户自定义函数作用到数组中的每个值上,并返回用户自定义函数作用后的带有新值的数组.
1 $callBackData = array_map(function($value){ 2 return $usernameData[] = $value[‘username‘]; 3 }, $data); 4 var_dump($callBackData);//array(4) { [0]=> string(6) "陈一" [1]=> string(6) "洪二" [2]=> string(6) "张三" [3]=> string(6) "李四" }
方法三: array_column函数方法 相对实现简单,但是要求PHP版本必须是5.5.0及以上版本
1 $usernameData = array_column($data, ‘username‘); 2 var_dump($usernameData);//array(4) { [0]=> string(6) "陈一" [1]=> string(6) "洪二" [2]=> string(6) "张三" [3]=> string(6) "李四" }
方法四: array_walk函数方法 函数对数组中的每个元素应用用户自定义函数.在函数中,数组的键名和键值是参数.
1 $usernameData = array(); 2 array_walk($data, function($value, $key) use (&$usernameData){ 3 $usernameData[] = $value[‘username‘]; 4 }); 5 var_dump($usernameData);//array(4) { [0]=> string(6) "陈一" [1]=> string(6) "洪二" [2]=> string(6) "张三" [3]=> string(6) "李四" }
原文地址:https://www.cnblogs.com/cxx8181602/p/9835944.html
时间: 2024-10-19 17:52:45