Suppose we have an array with one attribute for each element:
Array ( [0] => A [1] => B [2] => C [3] => D )
Is it possible to add the same uniform attribute to each of the elements, so that a new two-dimensional array would be obtained? Ie for attribute X:
Array ( [0] => Array ( [0] => A [1] => X)
[1] => Array ( [0] => B [1] => X)
[2] => Array ( [0] => C [1] => X) )
I know, I could do it using for each loop, but is there any more elegant solution (such as array_combine)?
(For assigning different values, please refer to: Assigning a value to each array element PHP )
You could use array_map :
$array = array ( 'A', 'B', 'C', 'D' );
$array = array_map(function($el) {
return array($el, 'X');
}, $array);
array_walk
could work as well.
$arr = array('A', 'B', 'C', 'D');
array_walk($arr, 'arrFunc');
function arrFunc(&$item, $key)
{
$item = array($item, 'X');
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.