How to merge a multidimensional array into one single dimension array - php

I have a multi dimension array that I want to merge all the inside arrays into one singer dimension array, I have tried array_merge with foreach but it doesn't help.
Example Array:
$nums = array (
array(1,2,3),
array(4,5,6),
array(7,8,9)
);
What I did but get an empty array
$newArr = [];
foreach ($nums as $value) {
array_merge($newArr, $value);
}
Expectation
$newArr = array(1,2,3,4,5,6,7,8,9)

You could use the function array_merge() this way :
$newArr = array_merge(...$nums)
It would make your code lighter and avoid the use of a foreach loop.

array_merge returns the results of the merge rather than acting on the passed argument like sort() does. You need to be doing:
$newArr = array_merge($newArr, $value);

Related

duplicating a value inside array with using a value in another array PHP

hi i have three array like this
$arr1 = array(2,3,4,5);
$arr2 = array(1,2,3,4);
$arr3 = array();
i need a loop function to duplicate each of the value inside $arr2 with the value inside $arr1 so the end result should look like this:
$arr3= array(1,1,2,2,2,3,3,3,3,4,4,4,4,4,4);
i know that i need to do an array_push into the $arr3 with $arr2[i] by doing this
for($i=0;$i < count($arr2);$++){
array_push($arr3,$arr2[$i]);
}
but i dont know the outer loop for iterating the array_push loop, what should i add to do the duplicating?
Solution 1: You need to apply a foreach() and for() loop
1.Iterate over the first array $arr1
2.Check that value with the same key of the first array exists or not in the second array
3.Apply a loop based on first array values
4.Assign same value repeatedly based on loop
foreach($arr1 as $key=>$arr){
if(isset($arr2[$key])){
for($i=0;$i<$arr;$i++){
$arr3[] = $arr2[$key];
}
}
}
print_r($arr3);
Output:-https://eval.in/1005648
Solution 2: You can use array_merge() and array_fill()
foreach($arr1 as $key=>$arr){
$arr3= array_merge($arr3,array_fill(count($arr3),$arr,$arr2[$key]));
}
echo "<pre/>";print_r($arr3);
Output:-https://eval.in/1005666

Get array number from Array with String value

I have an array with string value in PHP for example : arr['apple'], arr['banana'], and many more -about 20-30 data (get it from some process). Now I want to get its value and return it to one variable.
For example, I have Original array is like this:
$arr['Apple']
$arr['Banana']
and more..
and result that I want is like this:
$arr[0] = "Apple"
$arr[1] = "Banana"
and more..
Any idea how to do that?
Why not using array_keys()?
$new_array = array_keys($array);
Use array_flip()
$new_arr = array_flip($old_arr);
Demonstration
use foreach loop
foreach($arr as $key => $val){
$new_var[] = $key;
}
use array_keys function:
$keys = array_keys($arr);
It returns an array of all the keys in array.

PHP array_chunk and then array_merge

is there any way to merge undefined number of arrays? Array_merge doesn't work for me, cause you have to actually put those arrays as parameters, or maybe there is a way.
I've chunked an array into n - number of arrays, I do some stuff on those chunks and would like to merge some other arrays:
$chunky = array_chunk($positions);
$arraytomerge = array();
foreach($chunky as $key=>$val)
{
do some stuff with $keys and $vals
$arraytomerge[] = array('1','2','3','4');
}
$merged = array_merge($arraytomerge[0],$arraytomerge[1]...);
How to list arrays as array_merge parameters?
Instead of doing
//do some stuff with $keys and $vals
$arraytomerge[] = array('1','2','3','4');
Just do
//do some stuff with $keys and $vals
$merged = array_merge($merged,array('1','2','3','4'));
Or better yet, just add your new items directly to the $merged array instead of creating a new array

How can I delete array elements inside foreach loop?

I have a foreach loop and I would like to completely remove the array elements that satisfy the criteria, and change the keys to stay sequential 1,2,3,4.
I have:
$thearray = array(20,1,15,12,3,6,93);
foreach($thearray as $key => $value){
if($value < 10){
unset($thearray[$key]);
}
}
print_r($thearray);
But this keeps the keys as they were before. I want to make them 1,2,3,4, how can this be achieved?
Reset the array indices with array_values():
$thearray = array_values( $thearray);
print_r($thearray);
You can just use array_filter to remove the array elements that satisfy the criteria
$thisarray = array_filter($thearray,function($v){ return $v > 10 ;});
Then use array_values change the keys to stay 0, 1,2,3,4 .... as required
$thisarray = array_values($thisarray);
Build up a new array and then assign that to your original array after:
$thearray=array(20,1,15,12,3,6,93);
$newarray=array();
foreach($thearray as $key=>$value){
if($value>=10){
$newarray[]=$value
}
}
$thearray=$newarray;
print_r($thearray);

Convert array of single-element arrays to a one-dimensional array

I have this kind of an array containing single-element arrays:
$array = [[88868], [88867], [88869], [88870]];
I need to convert this to one dimensional array.
Desired output:
[88868, 88867, 88869, 88870]
Is there any built-in/native PHP functionality for this array conversion?
For your limited use case, this'll do it:
$oneDimensionalArray = array_map('current', $twoDimensionalArray);
This can be more generalized for when the subarrays have many entries to this:
$oneDimensionalArray = call_user_func_array('array_merge', $twoDimensionalArray);
The PHP array_mergeĀ­Docs function can flatten your array:
$flat = call_user_func_array('array_merge', $array);
In case the original array has a higher depth than 2 levels, the SPL in PHP has a RecursiveArrayIterator you can use to flatten it:
$flat = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)), 0);
See as well: Turning multidimensional array into one-dimensional array
try:
$new_array = array();
foreach($big_array as $array)
{
foreach($array as $val)
{
array_push($new_array, $val);
}
}
print_r($new_array);
$oneDim = array();
foreach($twoDim as $i) {
$oneDim[] = $i[0];
}
Yup.
$values = array(array(88868), array(88867), array(88869), array(88870));
foreach ($values as &$value) $value = $value[0];
http://codepad.org/f9KjbCCb
foreach($array as $key => $value){
//check that $value is not empty and an array
if (!empty($value) && is_array($value)) {
foreach ($value as $k => $v) {
//pushing data to new array
$newArray[] = $v;
}
}
}
For a two dimensional array this works as well:
array_merge(...$twoDimensionalArray)
While some of the answers on the page that was previously used to close this page did have answers that suited this question (like array_merge(...$array)). There are techniques for this specific question that do not belong on the other page because of the input data structure.
The sample data structure here is an array of single-element, indexed arrays.
var_export(array_column($array, 0));
Is all that this question requires.
If you ever have a daft job interview that asks you to do it without any function calls, you can use a language construct (foreach()) and use "array destructuring" syntax to push values into a result variable without even writing a body for the loop. (Demo)
$result = [];
foreach ($array as [$result[]]);
var_export($result);
Laravel also has a flattening helper method: Arr::flatten()

Categories