I have an array that may look like
$arr = array(
array(
'test1' => 'testing1'
),
array(
'test2' => array(
1 =>'testing2
)
);
and I want to turn it into
$newArr = array(
'test1' => 'testing1',
'test2' => array(
1 => 'testing2'
)
);
so i have been trying to shift all array elements up one level.
eidt:
this is my method that combines 2 array together:
public function arrayMerge($arr1, $arr2)
{
foreach($arr2 as $key => $value) {
$condition = (array_key_exists($key, $arr1) && is_array($value));
$arr1[$key] = ($condition ? $this->arrayMerge($arr1[$key], $arr2[$key]) : $value);
}
return $arr1;
}
The array_shift() function removes the first element from an array, and returns the value of the removed element. Note: If the keys are numeric, all elements will get new keys, starting from 0 and increases by 1 (See example below).
To shift the bits of array elements of a 2d array to the right, use the numpy. right_shift() method in Python Numpy. Bits are shifted to the right x2.
Answer: Use the PHP array_shift() function You can use the PHP array_shift() function to remove the first element or value from an array. The array_shift() function also returns the removed value of array. However, if the array is empty (or the variable is not an array), the returned value will be NULL .
It's somewhat trivial, many ways are possible.
For example using the array union operator (+
)Docs creating the union of all arrays inside the array:
$newArr = array();
foreach ($arr as $subarray)
$newArr += $subarray;
Or by using array_merge
Docs with all subarrays at once via call_user_func_array
Docs:
$newArray = call_user_func_array('array_merge', $arr);
Try
$arr = array(
array('test1' => 'testing1' ),
array('test2' => array(1 =>'testing2'))
);
$new = array();
foreach($arr as $value) {
$new += $value;
}
var_dump($new);
Output
array
'test1' => string 'testing1' (length=8)
'test2' =>
array
1 => string 'testing2' (length=8)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With