Ask for help on the question of appending elements to the header of php two-dimensional array

to append an element to a two-dimensional array. I don"t know why I can"t append it all the time. The similar code is as follows, mainly using the function array_unshift (). In the document, it is said that elements can be appended to the array.

<?php
$arr1 = ["0"=>["name"=>zhangsan,"sex"=>1],"1"=>["name"=>lisi,"sex"=>0],"2"=>["name"=>wangwu,"sex"=>1]];

$array2 = ["0"=>["name"=>zhaoliu,"sex"=>1],"1"=>["name"=>xiaoqi,"sex"=>1]];

//$arr2$arr1
:
foreach($array2 as $key=>$value){
    array_unshift($arr1,$value);
}

:
array_walk($array2,function($item) use ($arr1)){
    array_unshift($arr1,$item);
}


print $arr1 with a number instead of an appended new array; ask the master to analyze the cause or give a solution, thank you.

Mar.18,2021

you used use ($arr1) , which is just passed by value. You need to pass use (& $arr1)

by reference. The arguments to

array_unshift () are passed by reference, so the original array is changed directly, and the return value is just the number of elements in the array. print_r (array_unshift ()) only outputs numbers


Sorry, can you explain your second way of writing to me? Really do not understand, and the first method can be run to complete, but as for why not successful, can you write the code, as well as the printed results, send a screenshot to see.


clipboard.png
array_unshift returns the new number of arrays to be added, so a number is returned instead of the appended new array

Menu