首页  >  文章  >  后端开发  >  php内置函数array_column介绍

php内置函数array_column介绍

幸运切糕
幸运切糕原创
2020-05-02 20:24:59111浏览

    array_column是php的内置函数,用于返回多维数组中指定的一列,使用时需注意php版本 >= 5.5.0,低版本会报错:“no function”。


函数说明

array_column($array, $column1, $column2)

array_column() 返回数组array中键为column1的列, 如果指定了可选参数column2,那么column2还会被设置为返回列的键。


例1

<?php
$array = [
    [&#39;id&#39; => 100, &#39;name&#39; => &#39;test1&#39;, &#39;score&#39; => 1, &#39;money&#39; => 111],
    [&#39;id&#39; => 101, &#39;name&#39; => &#39;test2&#39;, &#39;score&#39; => 2, &#39;money&#39; => 222],
    [&#39;id&#39; => 102, &#39;name&#39; => &#39;test3&#39;, &#39;score&#39; => 3, &#39;money&#39; => 333],
];
$names = array_column($array, &#39;name&#39;);
print_r($names);

例1结果如下:

1.png

例2

<?php
$array = [
    [&#39;id&#39; => 100, &#39;name&#39; => &#39;test1&#39;, &#39;score&#39; => 1, &#39;money&#39; => 111],
    [&#39;id&#39; => 101, &#39;name&#39; => &#39;test2&#39;, &#39;score&#39; => 2, &#39;money&#39; => 222],
    [&#39;id&#39; => 102, &#39;name&#39; => &#39;test3&#39;, &#39;score&#39; => 3, &#39;money&#39; => 333],
];
$names = array_column($array, &#39;name&#39;, &#39;id&#39;);
print_r($names);

例2结果如下:

3.png

可以看到例2第三个参数‘id’对应的列,已经被置为了新数组的键,同时联想到thinkphp数据库操作的column方法不也是这个道理吗,如下:

微信截图_20200502202336.png

总的来说,array_column在处理数据时还是挺常用的,它没有使用foreach处理那么繁杂。但只有去深刻理解后,才能在项目总灵活运用,所以小伙伴儿们多多动手,印象才会更深刻哟!

以上就是php内置函数array_column介绍的详细内容,更多请关注php中文网其它相关文章!

以上是php内置函数array_column介绍的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn