Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> PHP

Hàm array_walk_recursive() trong PHP

Mô tả

Hàm array_walk_recursive() áp dụng hàm người dùng đệ quy cho mỗi phần tử mảng.

Cú pháp

array_walk_recursive(arr, custom_func, parameter)

Tham số

  • arr − Mảng chỉ định. Bắt buộc.

  • custom_func − Hàm do người dùng định nghĩa. Bắt buộc.

  • parameter − Tham số cho hàm tùy chỉnh. Tùy chọn.

Giá trị trả về

Trả về TRUE nếu thành công, FALSE nếu thất bại.

Ví dụ

<?php
function display($val, $key) {
    echo "Key $key with the value $val<br>";
}
$arr1 = array("p" => "accessories", "q" => "footwear");
$arr2 = array($arr1, "1" => "electronics");
array_walk_recursive($arr2, "display");
?>

Kết quả

Key p with the value accessories
Key q with the value footwear
Key 1 with the value electronics

Ví dụ khác (có tham số thêm)

<?php
function display($val, $key, $extra) {
    echo "Key $key $extra $val<br>";
}
$arr1 = array("p" => "accessories", "q" => "footwear");
$arr2 = array($arr1, "5" => "electronics");
array_walk_recursive($arr2, "display", "with value");
?>

Kết quả

Key p with the value accessories
Key q with the value footwear
Key 5 with the value electronics