文字

数组

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 对数组进行排序
  • 数组 函数
    • array_change_key_case — 返回字符串键名全为小写或大写的数组
    • array_chunk — 将一个数组分割成多个
    • array_column — 返回数组中指定的一列
    • array_combine — 创建一个数组,用一个数组的值作为其键名,另一个数组的值作为其值
    • array_count_values — 统计数组中所有的值出现的次数
    • array_diff_assoc — 带索引检查计算数组的差集
    • array_diff_key — 使用键名比较计算数组的差集
    • array_diff_uassoc — 用用户提供的回调函数做索引检查来计算数组的差集
    • array_diff_ukey — 用回调函数对键名比较计算数组的差集
    • array_diff — 计算数组的差集
    • array_fill_keys — 使用指定的键和值填充数组
    • array_fill — 用给定的值填充数组
    • array_filter — 用回调函数过滤数组中的单元
    • array_flip — 交换数组中的键和值
    • array_intersect_assoc — 带索引检查计算数组的交集
    • array_intersect_key — 使用键名比较计算数组的交集
    • array_intersect_uassoc — 带索引检查计算数组的交集,用回调函数比较索引
    • array_intersect_ukey — 用回调函数比较键名来计算数组的交集
    • array_intersect — 计算数组的交集
    • array_key_exists — 检查给定的键名或索引是否存在于数组中
    • array_keys — 返回数组中部分的或所有的键名
    • array_map — 将回调函数作用到给定数组的单元上
    • array_merge_recursive — 递归地合并一个或多个数组
    • array_merge — 合并一个或多个数组
    • array_multisort — 对多个数组或多维数组进行排序
    • array_pad — 用值将数组填补到指定长度
    • array_pop — 将数组最后一个单元弹出(出栈)
    • array_product — 计算数组中所有值的乘积
    • array_push — 将一个或多个单元压入数组的末尾(入栈)
    • array_rand — 从数组中随机取出一个或多个单元
    • array_reduce — 用回调函数迭代地将数组简化为单一的值
    • array_replace_recursive — 使用传递的数组递归替换第一个数组的元素
    • array_replace — 使用传递的数组替换第一个数组的元素
    • array_reverse — 返回一个单元顺序相反的数组
    • array_search — 在数组中搜索给定的值,如果成功则返回相应的键名
    • array_shift — 将数组开头的单元移出数组
    • array_slice — 从数组中取出一段
    • array_splice — 把数组中的一部分去掉并用其它值取代
    • array_sum — 计算数组中所有值的和
    • array_udiff_assoc — 带索引检查计算数组的差集,用回调函数比较数据
    • array_udiff_uassoc — 带索引检查计算数组的差集,用回调函数比较数据和索引
    • array_udiff — 用回调函数比较数据来计算数组的差集
    • array_uintersect_assoc — 带索引检查计算数组的交集,用回调函数比较数据
    • array_uintersect_uassoc — 带索引检查计算数组的交集,用回调函数比较数据和索引
    • array_uintersect — 计算数组的交集,用回调函数比较数据
    • array_unique — 移除数组中重复的值
    • array_unshift — 在数组开头插入一个或多个单元
    • array_values — 返回数组中所有的值
    • array_walk_recursive — 对数组中的每个成员递归地应用用户函数
    • array_walk — 使用用户自定义函数对数组中的每个元素做回调处理
    • array — 新建一个数组
    • arsort — 对数组进行逆向排序并保持索引关系
    • asort — 对数组进行排序并保持索引关系
    • compact — 建立一个数组,包括变量名和它们的值
    • count — 计算数组中的单元数目或对象中的属性个数
    • current — 返回数组中的当前单元
    • each — 返回数组中当前的键/值对并将数组指针向前移动一步
    • end — 将数组的内部指针指向最后一个单元
    • extract — 从数组中将变量导入到当前的符号表
    • in_array — 检查数组中是否存在某个值
    • key_exists — 别名 array_key_exists
    • key — 从关联数组中取得键名
    • krsort — 对数组按照键名逆向排序
    • ksort — 对数组按照键名排序
    • list — 把数组中的值赋给一些变量
    • natcasesort — 用“自然排序”算法对数组进行不区分大小写字母的排序
    • natsort — 用“自然排序”算法对数组排序
    • next — 将数组中的内部指针向前移动一位
    • pos — current 的别名
    • prev — 将数组的内部指针倒回一位
    • range — 建立一个包含指定范围单元的数组
    • reset — 将数组的内部指针指向第一个单元
    • rsort — 对数组逆向排序
    • shuffle — 将数组打乱
    • sizeof — count 的别名
    • sort — 对数组排序
    • uasort — 使用用户自定义的比较函数对数组中的值进行排序并保持索引关联
    • uksort — 使用用户自定义的比较函数对数组中的键名进行排序
    • usort — 使用用户自定义的比较函数对数组中的值进行排序

用户评论:

[#1] Anonymous [2014-10-23 07:36:52]

And which php version where added short array creating form:
$myArr = [];

?

[#2] gratcypalma at gmail dot com [2013-09-09 09:57:15]

<?php
function foo() {
return array('name' => 'palma', 'old' => 23, 'language' => 'PHP');
}

$a = foo();
var_dump($a['name']);



var_dump(foo()['name']);

[#3] spereversev at envionsoftware dot com [2012-07-10 10:29:10]

<?php
function array_mask(array $array, array $keys) {
    return 
array_intersect_key$arrayarray_fill_keys$keys) );
}
?>


Might be helpful to take a part of associative array containing given keys, for example, from a $_REQUEST array

array_mask($_REQUEST, array('name', 'email'));

[#4] info at curtinsNOSPAMcreations dot com [2010-11-05 07:49:12]

Another way to create a multidimensional array that looks a lot cleaner is to use json_decode.  (Note that this probably adds a touch of overhead, but it sure does look nicer.)  You can of course add as many levels and as much formatting as you'd like to the string you then decode.  Don't forget that json requires " around values, not '!!  (So, you can't enclose the json string with " and use ' inside the string.)

As an example:

<?php
    $myarray
['blah'] = json_decode('[
        {"label":"foo","name":"baz"},
        {"label":"boop","name":"beep"}
    ]'
,true);

print_r($myarray)
?>

returns:

Array
(
    [blah] => Array
        (
            [0] => Array
                (
                    [label] => foo
                    [name] => baz
                )
 
            [1] => Array
                (
                    [label] => boop
                    [name] => beep
                )
        )
)

[#5] dragos dot rusu at NOSPAM dot bytex dot ro [2010-03-07 06:15:34]

If an array item is declared with key as NULL, array key will automatically be converted to empty string '', as follows:

<?php
$a = array(
NULL => 'zero',
1    => 'one',
2    => 'two');

// This will show empty string for key associated with "zero" value
var_dump(array_keys($a));

// Array elements are shown
reset($a);
while( key($a) !== NULL )
{
  echo key($a) . ": ".current($a) . "<br>";// PHP_EOL
  next($a);
}

// Array elements are not shown
reset($a);
while( key($a) != NULL ) // '' == null   => no iteration will be executed
{
  echo key($a) . ": ".current($a) . "<br>";// PHP_EOL
  next($a);
}

[#6] John Marc [2010-02-15 13:30:25]

Be careful when adding elements to a numeric array.
I wanted to store some info about some items from a database and decided to use the record id as a key.

<?php
$key
=3000000000;
$DATA[$key]=true;
?>


This will create an array of 30 million elements and chances are, you will use up all memory with these 2 lines

<?php
$key
=3000000000;
$DATA["$key"]=true;
?>


This on the other hand will force the array to be an associative array and will only create the one element

[#7] sunear at gmail dot com [2009-08-04 10:45:52]

Made this function to delete elements in an array;

<?php

function array_del_elm($input_array$del_indexes) {
    if (
is_array($del_indexes)) {
        
$indexes $del_indexes;
    } elseif(
is_string($del_indexes)) {
        
$indexes explode($del_indexes" ");
    } elseif(
is_numeric($del_indexes)) {
        
$indexes[0] = (integer)$del_indexes;
    } else return;
    
$del_indexes null;
    
    
$cur_index 0;
    if (
sort($indexes)) for($i=0$i<count($input_array); $i++) {
        if (
$i == $indexes[$cur_index]) {
            
$cur_index++;
            if (
$cur_index == count($indexes)) return $output_array;
            continue;
        }
        
$output_array[] = $input_array[$i];
    }
    return 
$output_array;
}

?>


but then i saw the methods of doing the same by Tyler Bannister & Paul, could see that theirs were faster, but had floors regarding deleting multiple elements thus support of several ways of giving parameters. I combined the two methods to this to this:

<?php

function array_del_elm($target_array$del_indexes) {
    if (
is_array($del_indexes)) {
        
$indexes $del_indexes;
    } elseif(
is_string($del_indexes)) {
        
$indexes explode($del_indexes" ");
    } elseif(
is_numeric($del_indexes)) {
        
$indexes[0] = (integer)$del_indexes;
    } else return;
    unset(
$del_indexes);
    
    for(
$i=0$i<count($indexes); $i++) {
        unset(
$target_array[$indexes[$i]]);
    }
    return 
$target_array;
}

?>


Fast, compliant and functional ;)

[#8] Tyler Bannister [2009-06-11 06:59:56]

To delete an individual array element use the unset function

For example:

<?PHP
    $arr 
= array( "A""B""C" );
    unset( 
$arr[1] );
    
// now $arr = array( "A", "C" );
?>


Unlink is for deleting files.

[#9] thomasdecaux at ebuildy dot com [2009-05-15 01:14:21]

To browse a simple array:

<?php

foreach ($myArray AS $myItem)
{

}

?>


To browse an associative array:

<?php

foreach ($myArray AS $key=>$value)
{

}

?>


http://www.ebuildy.com

[#10] macnimble at gmail dot com [2009-03-27 06:59:30]

Converting a linear array (like a mysql record set) into a tree, or multi-dimensional array can be a real bugbear. Capitalizing on references in PHP, we can 'stack' an array in one pass, using one loop, like this:

<?php
# array_stack()
# Original idea from:
# http://www.ideashower.com/our_solutions/
#   create-a-parent-child-array-structure-in-one-pass/
function array_stack (&$a$p '@parent'$c '@children')
{
  
$l $t = array();
  foreach (
$a AS $key => $val):
    if (!
$val[$p]) $t[$key] =& $l[$key];
    else 
$l[$val[$p]][$c][$key] =& $l[$key];
    
$l[$key] = (array)$l[$key] + $val;
  endforeach;
  return 
$a = array('tree' => $t'leaf' => $l);
}

# Example:
$node = array();
$node[1] = array('@parent' => 0'title' => 'I am node 1.');
#     ^-----------------------v Link @parent value to key.
$node[2] = array('@parent' => 1'title' => 'I am node 2.');
$node[3] = array('@parent' => 2'title' => 'I am node 3.');
$node[4] = array('@parent' => 1'title' => 'I am node 4.');
$node[5] = array('@parent' => 4'title' => 'I am node 5.');

array_stack($node);

$node['leaf'][1]['title'] = 'I am node one.';
$node['leaf'][2]['title'] = 'I am node two.';
$node['leaf'][3]['title'] = 'I am node three.';
$node['leaf'][4]['title'] = 'I am node four.';
$node['leaf'][5]['title'] = 'I am node five.';

echo 
'<pre>',print_r($node['tree'],TRUE),'</pre>';
?>


Note that there's no parameter checking on the array value, but this is only to keep the function size small. One could easily a quick check in there to make sure the $a parameter was in fact an array.

Hope you find it useful. Huge thanks to Nate Weiner of IdeaShower.com for providing the original function I built on.

[#11] andyd273 at gmail dot com [2009-02-24 13:12:17]

A small correction to Endel Dreyer's PHP array to javascript array function. I just changed it to show keys correctly:

            function array2js($array,$show_keys)
            {
                $dimensoes = array();
                $valores = array();
               
                $total = count ($array)-1;
                $i=0;
                foreach($array as $key=>$value){
                    if (is_array($value)) {
                        $dimensoes[$i] = array2js($value,$show_keys);
                        if ($show_keys) $dimensoes[$i] = '"'.$key.'":'.$dimensoes[$i];
                    } else {
                        $dimensoes[$i] = '"'.addslashes($value).'"';
                        if ($show_keys) $dimensoes[$i] = '"'.$key.'":'.$dimensoes[$i];
                    }
                    if ($i==0) $dimensoes[$i] = '{'.$dimensoes[$i];
                    if ($i==$total) $dimensoes[$i].= '}';
                    $i++;
                }
                return implode(',',$dimensoes);
            }

[#12] Anonymous [2008-11-26 10:36:51]

@jorge at andrade dot cl
This variant is faster:
<?php
function array_avg($array,$precision=2){
    if(!
is_array($array))
        return 
'ERROR in function array_avg(): this is a not array';

    foreach(
$array as $value)
        if(!
is_numeric($value))
            return 
'ERROR in function array_avg(): the array contains one or more non-numeric values';
    
    
$cuantos=count($array);
  return 
round(array_sum($array)/$cuantos,$precision);
}
?>

[#13] webmaster at infoproducts dot x10hosting dot com [2008-10-10 19:13:27]

New value can also be added to the array as shown below.
$theVariable["google"] = "http//google.com";
or
$theVariable["1"] = "http//google.com";

[#14] Jack A [2008-10-07 08:14:21]

Note that arrays are not allowed in class constants and trying to do so will throw a fatal error.

[#15] contact at greyphoenix dot biz [2008-06-30 21:36:03]

<?php
//Creating a multidimensional array

$theVariable = array("Search Engines" => 
array (
    
0=> "http//google.com"
    
1=> "http//yahoo.com",
    
2=> "http//msn.com/"),

"Social Networking Sites" =>
array (
    
=> "http//www.facebook.com",
    
=> "http//www.myspace.com",
    
=> "http//vkontakte.ru",)
);

echo 
"The first array value is " $theVariable['Search Engines'][0];
?>


-- Output--
The first array value is http://google.com

[#16] applegrew at rediffmail dot com [2008-05-28 08:23:27]

For newbies like me.

Creating new arrays:-
//Creates a blank array.
$theVariable = array();

//Creates an array with elements.
$theVariable = array("A", "B", "C");

//Creating Associaive array.
$theVariable = array(1 => "http//google.com", 2=> "http://yahoo.com");

//Creating Associaive array with named keys
$theVariable = array("google" => "http//google.com", "yahoo"=> "http://yahoo.com");

Note:
New value can be added to the array as shown below.
$theVariable[] = "D";
$theVariable[] = "E";

上一篇: 下一篇: