php实现快速对二维数组某一列进行组装的方法小结
吾爱主题
阅读:155
2021-09-18 16:51:00
评论:0
本文实例总结了php实现快速对二维数组某一列进行组装的方法。分享给大家供大家参考,具体如下:
问题:
比如我二维数组是这样的:
?1 2 3 4 5 6 7 | $user = array ( '0' => array ( 'id' =>100, 'username' => 'a1' ), '1' => array ( 'id' =>101, 'username' => 'a2' ), '2' => array ( 'id' =>102, 'username' => 'a3' ), '3' => array ( 'id' =>103, 'username' => 'a4' ), '4' => array ( 'id' =>104, 'username' => 'a5' ), ) |
如何快速的获取所有id组成的ids字符串,比如$ids='100,101,102,103,104'; 再者如果我有条件的组装,比如id!=103等这样的,除了循环处理外有没有比较方便快速的方法?
解决方法:
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | $user = array ( '0' => array ( 'id' =>100, 'username' => 'a1' ), '1' => array ( 'id' =>101, 'username' => 'a2' ), '2' => array ( 'id' =>102, 'username' => 'a3' ), '3' => array ( 'id' =>103, 'username' => 'a4' ), '4' => array ( 'id' =>104, 'username' => 'a5' ), ); /** * @param array $array 数组 * @param string $k 要获取值的key * @param array $rm 要去除的数据 * */ function array_get_v( $array , $k , $rm ) { if (!trim( $k )) return false; preg_match_all( "/\"$k\":(\d+)/" , json_encode( $array ), $res ); $res = array_diff ( $res [1], $rm ); return implode( ',' , $res ); } print_r(array_get_v( $user , 'id' , array (101))); |
运行结果:
100,102,103,104
补充方法:
例1:
?1 2 3 4 5 6 7 8 9 10 11 | $user = array ( '0' => array ( 'id' => 100, 'username' => 'a1' ), '1' => array ( 'id' => 101, 'username' => 'a2' ), '2' => array ( 'id' => 102, 'username' => 'a3' ), '3' => array ( 'id' => 103, 'username' => 'a4' ), '4' => array ( 'id' => 104, 'username' => 'a5' ), ); array_walk ( $user , function ( $v , $k ) use (& $ids ){ $ids [ $k ] = $v [ 'id' ]; }); echo implode( ',' , $ids ); |
运行结果:
100,101,102,103,104
例2:
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?php function process( $v ){ //如果要加限制条件,在这里加入即可 if (isset( $v [ 'id' ])) return $v [ 'id' ]; } $user = array ( '0' => array ( 'id' => 100, 'username' => 'a1' ), '1' => array ( 'id' => 101, 'username' => 'a2' ), '2' => array ( 'id' => 102, 'username' => 'a3' ), '3' => array ( 'id' => 103, 'username' => 'a4' ), '4' => array ( 'id' => 104, 'username' => 'a5' ), ); $aUser = array_map ( "process" , $user ); echo implode( ',' , $aUser ); |
运行结果:
100,101,102,103,104
希望本文所述对大家PHP程序设计有所帮助。
原文链接:http://www.dewen.net.cn/q/5090/php+%E5%BF%AB%E9%80%9F%E7%9A%84%E5%AF%B9%E4%BA%8C%E7%BB%B4%E6%95%B0%E7%BB%84%E6%9F%90%E4%B8%80%E5%88%97%E8%BF%9B%E8%A1%8C%E7%BB%84%E8%A3%85%E7%9A%84%E6%96%B9%E6%B3%95
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。