Home  >  Article  >  Backend Development  >  PHP study notes: Definition and traversal of arrays_PHP tutorial

PHP study notes: Definition and traversal of arrays_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:50:45909browse

Array in php is a special data type, which can be said to be an object or a memory. It can store the content of other data types in php, such as an array can contain characters, numbers, objects, etc. Wait, let me first learn the definition and traversal search of php arrays.

① The first method of creating an array

$arr[0]=123;
$arr[1]=90;
….

Concept:
[0] -> We call this subscript, or keyword
$arr[0] -> This is called an element of the array.
$arr[0]=123; 123 means the value corresponding to the $arr[0] element
$arr –》This is the name of the array.
☞In PHP arrays, the value stored in an element can be of any data type

② The second way to create an array

Basic Grammar
$array name=array(value 1, value 2,....);
Example:
$arr=array(1,90,"helllo",89.5);


③ The third way to create an array (By default, the subscripts of our elements are numbered starting from 0, but in fact, you can also specify it yourself)


Basic syntax $arr[‘logo’]=”Beijing”;
$arr[’hsp’]=123;
....
or
$arr=array("logo"=>"Beijing","hsp"=>123,4=>678);

Array traversal method:


Note: If you use for while do..while, you must make sure that the subscripts of the array are arranged sequentially starting from 0
To find out how many elements there are in the array, you can use the system function count

//

The code is as follows Copy code
 代码如下 复制代码

for循环遍历方法
for($i=0;$i echo '
'.$arr[$i];
}

//while循环遍历方法
$i=0;//循环控制变量
while($i echo "
".$colors[$i];
$i++;
}

//do..while
$i=0;//循环控制变量
do{
echo "
".$colors[$i];
$i++;
}while($i

//foreach 遍历方法
这个foreach适用范围更广
foreach($arr as $key=>$val){
echo $key."=".$val."
";
}

For loop traversal method

for($i=0;$i echo '
'.$arr[$i]; }

//while loop traversal method
$i=0;//Loop control variable
while($i echo "
".$colors[$i];
$i++;
}

//do..while
$i=0;//Loop control variable
do{
echo "
".$colors[$i];

$i++;

}while($i //foreach traversal method

This foreach has a wider scope of application

foreach($arr as $key=>$val){

echo $key."=".$val."
";
 代码如下 复制代码

$arr_a = array(0 => "a", 1 => "b", 2 => "c");
$key = array_search("a", $arr_a);
if( $key !== FALSE ){
    echo "键名为:$key";
} else {
    echo '无匹配结果';
}
?>

}
php array related functions ① count function The basic usage is count($array name); can count how many elements there are in the array. ② is_array ③ print_r and var_dump ④ explode split the string Case: $str="Zhejiang&Taizhou&Hangzhou"; //In actual development, when it comes to string splitting, you can consider $arr=explode("&",$str); print_r($arr); Array search Example:
The code is as follows Copy code
$arr_a = array(0 => "a", 1 => "b", 2 => "c"); $key = array_search("a", $arr_a); if( $key !== FALSE ){ echo "Key name: $key"; } else { echo 'No matching results'; } ?>

The example output results are as follows:

Key name: 0

array_key_exists() function


The function array_key_exists() returns true if a specified key is found in an array, false otherwise. Its form is as follows:

boolean array_key_exists(mixed key,array array);

The following example will search for apple in the array key, and if found, will output the color of the fruit:

The code is as follows Copy code
 代码如下 复制代码

$fruit["apple"] = "red";
$fruit["banana"] = "yellow";
$fruit["pear"] = "green";
if(array_key_exists("apple", $fruit)){
 printf("apple's color is %s",$fruit["apple"]);
}

$fruit["apple"] = "red";

$fruit["banana"] = "yellow";

$fruit["pear"] = "green";

if(array_key_exists("apple", $fruit)){

printf("apple's color is %s",$fruit["apple"]);

}


The result of executing this code: apple's color is red



Merge arrays

The array_merge() function merges arrays together and returns a combined array. The resulting array starts with the first input array parameter, and is added sequentially in the order in which subsequent array parameters appear. Its form is:

Php code

array array_merge (array array1 array2…,arrayN)

 代码如下 复制代码

$fruits = array("apple","banana","pear");
$numbered = array("1","2","3");
$cards = array_merge($fruits, $numbered);
print_r($cards);

// output
// Array ( [0] => apple [1] => banana [2] => pear [3] => 1 [4] => 2 [5] => 3 )
?>

This function combines the cells of one or more arrays, and the values ​​in one array are appended to the previous array. Returns the resulting array.

If there is the same string key name in the input array, the value after the key name will overwrite the previous value. However, if the array contains numeric keys, the subsequent values ​​will not overwrite the original values, but will be appended to them.

If only an array is given and the array is numerically indexed, the key names are re-indexed consecutively.

The code is as follows Copy code
$fruits = array("apple","banana","pear");

$numbered = array("1","2","3");

$cards = array_merge($fruits, $numbered);

print_r($cards);

//output
代码如下 复制代码

$fruit1 = array("apple" => "red", "banana" => "yellow");
$fruit2 = array("pear" => "yellow", "apple" => "green");
$result = array_merge_recursive($fruit1, $fruit2);
print_r($result);

// output
// Array ( [apple] => Array ( [0] => red [1] => green ) [banana] => yellow [pear] => yellow )
?>   

// Array ( [0] => apple [1] => banana [2] => pear [3] => 1 [4] => 2 [5] => 3 ) ?> 2. Append array The array_merge_recursive() function is the same as array_merge(). It can merge two or more arrays together to form a combined array. The difference between the two is that the function will handle it differently when a key in an input array already exists in the result array. array_merge() will overwrite the previously existing key/value pairs and replace them with the key/value pairs in the current input array, while array_merge_recursive() will merge the two values ​​together to form a new array with the original keys. as an array name. There is also a form of array merging, which is to recursively append arrays. Its form is: Php code array array_merge_recursive(array array1,array array2[…,array arrayN]) The program example is as follows:
The code is as follows Copy code
$fruit1 = array("apple" => "red", "banana" => "yellow"); $fruit2 = array("pear" => "yellow", "apple" => "green"); $result = array_merge_recursive($fruit1, $fruit2); print_r($result); //output // Array ( [apple] => Array ( [0] => red [1] => green ) [banana] => yellow [pear] => yellow ) ?>

Now the key apple points to an array consisting of two indexed arrays of color values.

3. Connect arrays
The array_combine() function will get a new array, which consists of a set of submitted keys and corresponding values. Its form is:

array array_combine(array keys,array values)

Note that the two input arrays must be of the same size and cannot be empty. An example is as follows

The code is as follows Copy code
 代码如下 复制代码


$name = array("apple", "banana", "orange");
$color = array("red", "yellow", "orange");
$fruit = array_combine($name, $color);
print_r($fruit);

// output
// Array ( [apple] => red [banana] => yellow [orange] => orange )
?>

 

$name = array("apple", "banana", "orange"); $color = array("red", "yellow", "orange");

$fruit = array_combine($name, $color);

print_r($fruit);

//output

// Array ( [apple] => red [banana] => yellow [orange] => orange )

?>

 代码如下 复制代码

$fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon");
$subset = array_slice($fruits, 3);
print_r($subset);

// output
// Array ( [0] => Pear [1] => Grape [2] => Lemon [3] => Watermelon )
?>

4. Split array array_slice()
The array_slice() function will return a part of the array, starting from the key offset and ending at offset+length. Its form:

Php code

array array_slice (array array, int offset[,int length])

When offset is a positive value, splitting will start from the offset position from the beginning of the array; if offset is a negative value, splitting will start from the offset position from the end of the array. If the optional length parameter is omitted, the split will start at offset and go to the last element of the array. If length is given and is positive, it ends at offset+length from the beginning of the array. Conversely, if length is given and is negative, it ends at count(input_array)-|length| from the beginning of the array. Consider an example:

The code is as follows Copy code
$fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon"); $subset = array_slice($fruits, 3);

print_r($subset);

//output
代码如下 复制代码

$arr = array(
‘d’ => array(‘id’ => 5, ‘name’ => 1, ‘age’ => 7),
‘b’ => array(‘id’ => 2,’name’ => 3,’age’ => 4),
‘a’ => array(‘id’ => 8,’name’ => 10,’age’ => 5),
‘c’ => array(‘id’ => 1,’name’ => 2,’age’ => 2)
);

// Array ( [0] => Pear [1] => Grape [2] => Lemon [3] => Watermelon ) ?> Array sorting (the following method is used for one-dimensional arrays) •The sort() function is used to sort array cells from low to high. •rsort() function is used to sort array cells from high to low. •asort() function is used to sort array cells from low to high and maintain index relationship. •The arsort() function is used to sort the array cells from high to low and maintain the index relationship. •The ksort() function is used to sort array cells from low to high by key name. •The krsort() function is used to sort array cells from high to low by key name. Multidimensional array sorting For example, there is a mostly array:
The code is as follows Copy code
$arr = array( ‘d’ => array(‘id’ => 5, ‘name’ => 1, ‘age’ => 7), ‘b’ => array(‘id’ => 2, ‘name’ => 3, ‘age’ => 4), ‘a’ => array(‘id’ => 8, ‘name’ => 10, ‘age’ => 5), ‘c’ => array(‘id’ => 1, ‘name’ => 2, ‘age’ => 2) );

Need to sort the age items in the two-dimensional array.

You need to use PHP’s built-in function array_multisort(), you can read the manual.

Custom function:

function multi_array_sort($multi_array,$sort_key,$sort=SORT_ASC){
if(is_array($multi_array)){
foreach ($multi_array as $row_array){
if(is_array($row_array)){
$key_array[] = $row_array[$sort_key];
}else{
return false;
}
}
}else{
return false;
}
array_multisort($key_array,$sort,$multi_array);
return $multi_array;
}
The code is as follows
 代码如下 复制代码

function multi_array_sort($multi_array,$sort_key,$sort=SORT_ASC){
if(is_array($multi_array)){
foreach ($multi_array as $row_array){
if(is_array($row_array)){
$key_array[] = $row_array[$sort_key];
}else{
return false;
}
}
}else{
return false;
}
array_multisort($key_array,$sort,$multi_array);
return $multi_array;
}

//处理

echo “

”;
print_r(multi_array_sort($arr,’age’));exit;

//输出

Array
(
[c] => Array
(
[id] => 1
[name] => 2
[age] => 2
)

[b] => Array
(
[id] => 2
[name] => 3
[age] => 4
)

[a] => Array
(
[id] => 8
[name] => 10
[age] => 5
)

[d] => Array
(
[id] => 5
[name] => 1
[age] => 7
)

)

Copy code

//Processing

echo “

”;
print_r(multi_array_sort($arr,’age’));exit;

Array
(
[c] => Array
(
[id] => 1
[name] => 2
[age] => 2
)
[b] => Array
(
[id] => 2
[name] => 3
[age] => 4
)
[a] => Array
(
[id] => 8
[name] => 10
[age] => 5
)
[d] => Array
(
[id] => 5
[name] => 1
[age] => 7
)
)
written by Daewoo
http://www.bkjia.com/PHPjc/632628.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632628.htmlTechArticleArray in php is a special data type. It can be said to be an object or a memory. It can Store content of other data types in php, such as an array that can contain character types...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn