在PHP中,我们可以使用数组来存储和操作数据库查询的结果,以下是一些常见的PHP数组函数和它们的用法:

php 数据库 数组_PHPphp 数据库 数组_PHP(图片来源网络,侵删)

1、array_push():向数组末尾添加一个或多个元素。

$arr = array("apple", "banana");
array_push($arr, "orange", "grape");
print_r($arr);

输出结果:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => grape
)

2、array_pop():删除并返回数组最后一个元素。

$arr = array("apple", "banana", "orange", "grape");
$last = array_pop($arr);
print_r($arr);
echo $last;

输出结果:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
)
grape

3、array_shift():删除并返回数组第一个元素。

$arr = array("apple", "banana", "orange", "grape");
$first = array_shift($arr);
print_r($arr);
echo $first;

输出结果:

Array
(
    [0] => banana
    [1] => orange
    [2] => grape
)
apple

4、array_unshift():在数组开头添加一个或多个元素。

$arr = array("banana", "orange", "grape");
array_unshift($arr, "apple", "pear");
print_r($arr);

输出结果:

Array
(
    [0] => apple
    [1] => pear
    [2] => banana
    [3] => orange
    [4] => grape
)

5、in_array():检查数组中是否存在指定的值。

$arr = array("apple", "banana", "orange", "grape");
if (in_array("banana", $arr)) {
    echo "banana is in the array";
} else {
    echo "banana is not in the array";
}

输出结果:

banana is in the array

6、array_search():在数组中查找指定的值,如果找到则返回对应的键名。

$arr = array("apple", "banana", "orange", "grape");
$key = array_search("orange", $arr);
echo "The key of 'orange' is: " . $key;

输出结果:

The key of 'orange' is: 2

7、array_keys():返回数组中所有的键名。

$arr = array("apple" => 1, "banana" => 2, "orange" => 3, "grape" => 4);
$keys = array_keys($arr);
print_r($keys);

输出结果:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => grape
)

8、array_values():返回数组中所有的值。

$arr = array("apple" => 1, "banana" => 2, "orange" => 3, "grape" => 4);
$values = array_values($arr);
print_r($values);

输出结果:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

9、array_merge():合并两个或多个数组。

$arr1 = array("apple", "banana");
$arr2 = array("orange", "grape");
$merged = array_merge($arr1, $arr2);
print_r($merged);

输出结果:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => grape
)

10、array_slice():从数组中提取指定范围的元素。

$arr = array("apple", "banana", "orange", "grape");
$sliced = array_slice($arr, 1, 2);
print_r($sliced);

输出结果:

Array
(
    [0] => banana
    [1] => orange
)
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。