php5.5发布了,其中增加了一个新的数组函数array_column,感觉不错的!但是低版本php要使用,得自己实现:
参考地址:
复制代码 代码如下:
if(!function_exists(‘array_column’)){
function array_column($input, $columnkey, $indexkey=null){
$columnkeyisnumber = (is_numeric($columnkey)) ? true : fal;
$indexkeyisnull = (is_null($indexkey)) ? true : fal;
$indexkeyisnumber = (is_numeric($indexkey)) ? true : fal;
$result = array();
foreach((array)$input as $key=>$row){
if($columnkeyisnumber){
$tmp = array_slice($row, $columnkey, 1);
$tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : null;
}el{
$tmp = ist($row[$columnkey]) ? $row[$columnkey] : null;
}
if(!$indexkeyisnull){
if($indexkeyisnumber){
$key = array_slice($row, $indexkey, 1);
$key = (is_array($key) && !empty($key)) ? current($key) : null;
$key = is_null($key) ? 0 : $key;
}el{
$key = ist($row[$indexkey]) ? $row[$indexkey] : 0;
}
}
$result[$key] = $tmp;
}
return $result;
}
}
// 使用例子
$records = array(
array(
‘id圣诞主题’ => 2135,
‘first_name’ => ‘john’,
‘last_name’ =>上联贴左边还是右边; ‘doe’
),
array(
‘id’ => 3245,
‘first_name’ => ‘sally’,
‘last_name’ => ‘smith’
),
array(
‘id’ => 5342,
‘first_name’ => ‘jane’,
‘last_name’ => ‘jones’
),
array(
‘id’ => 5623,
‘first_name’ => ‘peter’,
‘last_name’ => ‘doe’
)
);
$firstnames = array_column($records, ‘first_name’);
print_r($firstnames);
/*
array
(
[0] => john
[1] => sally
[2] => jane
[3] => peter
)
*/
$records = array(
array(1, ‘john’, ‘doe’),
array(2, ‘sally’, ‘smith’),
array(3, ‘jane’, ‘jones’)
);
$lastnames = array_column($records, 2);
print_r($lastnames);
/*
array
(
[0] => doe
[1] => smith
[2] => jones
)
*/
$mismatchedcolumns = array(
array(
‘a’ => ‘foo’,
‘b’ => ‘bar’,
‘e’ => ‘baz’
),
array(
‘a’ => ‘qux’,
‘c’ => ‘quux’,
‘d’ => ‘corge’
),
array(酝酿怎么读
‘a’ => ‘grault’,
‘b’ => ‘garply’,
‘e’ => ‘waldo’
),
);
$foo = array_column($mismatchedcolumns, ‘a’, ‘b’);
print_r($foo);
/*
array
(
[bar] => foo
[0] => qux
[garply] => grault
)
*/
array_column 用于获取二维数组中的元素(php 5 >= 5.5.0)
复制代码 代码如下:
<?php
// array reprenting a possible record t returned from a databa
$records = array(
array(
‘id’ => 2135,
‘first_name’ => ‘john’,
‘last_name’ => ‘doe’,
),
array(
‘id’ => 3245,
‘first_name’ => ‘sally’,
‘last_name’ =>无私的反义词是什么; ‘smith&excel记账凭证模板#8217;,
),
array(
‘id’ => 5342,
‘first_name’ => ‘jane’,
‘last_name’ => ‘jones’,
),
array(
‘id’ => 5623,
‘first_name’ => ‘peter’,
‘last_name’ => ‘doe’,
)
);
$first_names = array_column($records, ‘first_name’);
print_r($first_names);
?>
array
(
[0] => john
[1] => sally
[2] => jane
[3] => peter
)<?php
// using the $records array from example #1
$last_names = array_column($records, ‘last_name’, ‘id’);
print_r($last_names);
?>
array
(
[2135] => doe
[3245] => smith
[5342] => jones
[5623] => doe
)
本文发布于:2023-04-06 09:52:34,感谢您对本站的认可!
本文链接:https://www.wtabcd.cn/fanwen/zuowen/a268c8c226f0a80eb063f38d457dfe89.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文word下载地址:php5.5新数组函数array.doc
本文 PDF 下载地址:php5.5新数组函数array.pdf
留言与评论(共有 0 条评论) |