Array operation PHP [duplicate] - php

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()

Related

How to merge a multidimensional array into one single dimension array

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);

Individually sorting subarrays of an array in PHP

I have an array of numeric subarrays. I want to sort all the subarrays, and then sort the whole array, and remove duplicates. Using sort($val) doesn't work, so I found the following workaround with $derp, which I find insanely stupid:
$arr = array( array(5,6), array(1,2), array(6,5) );
foreach ($arr as $key => $val) {
$derp = $val;
sort($derp);
$arr[$key] = $derp;
}
sort($arr);
$arr = array_map("unserialize", array_unique(array_map("serialize", $arr)));
The result is array( array(1,2), array(5,6) ). Is that is the correct way to do this in PHP, or is there a better and shorter way?
I created a pastebin as a response to the first answer: pastebin.com/Y5vNvKKL
This question is not anymore just about a less goofy way to write this: Now the question is:Why does sort() in array_work() not give the same result as sort() in foreach?
By the way: This is about finding the partitions of multisets.
I'd approach it like this:
array_walk($arr, 'sort');
$deduped = array();
foreach ($arr as $val) {
$deduped[serialize($val)] = $val;
}
$arr = array_values($deduped);

Array of values from and array of arrays without loops

Let's say I have a data set in PHP that is in the form of:
$array = [{"prior":"0","id":"61039","type":"todo"},
{"prior":"1","id":"70341","type":"todo"},
{"prior":"3","id":"39104","type":"todo"},
{"prior":"4","id":"70315","type":"todo"},
{"prior":"6","id":"72050","type":"todo"},
{"prior":"7","id":"72329","type":"todo"},
{"prior":"8","id":"73992","type":"todo"}]
I want to process this array of arrays so that I have a single array with integer indexes and the values of only id.
It's trivial to simple use loops:
$data = array();
foreach($array as $item){
$data[] = $item['id'];
}
What I want to know, is there a way to do this, disregarding efficiency, using the built in array functions of PHP (with no loops), or am I stuck using the foreach loop?
You can use array_map() for this:
$data = array_map(function ($el) { return $el['id']; }, $array);
Note that this still has to perform the looping internally; it's just not shown explicitly as in a foreach loop. This approach will be far less efficient than a plain 'ol foreach.
Demo
With PHP >= 5.5.0:
$array = json_decode($array, true);
$ids = array_column($array, 'id');

Storing array data in foreach loop in PHP

I am wondering how can I store all values from a foreach loop, I know that I am re-initialising in the loop but I'm not sure how to store the data. Heres my basic loop:
$array = array("v1", "v2", "v3", "v4");
foreach($array as $row){
$arr = array('val' => $row);
echo $row;
}
print_r($arr);
So when I use the print_r($arr) the only thing outputted would be v4 and I know that the values are there because the echo $row; does return each output individually.
My question would be how can I store each instance of row in my array?
Create a new array, fill it:
$array = array("v1", "v2", "v3", "v4");
$newArray = array();
foreach($array as $row){
// notice the brackets
$newArray[] = array('val' => $row);
}
print_r($newArray);
It looks like you are storing your array wrong.
Try adjusting the $arr = array('val' => $row);
to:
$arr[] = array('val' => $row);
This will set it so you pick up each line as a separate array which you can easily navigate through.
Hope this helps!
If I'm reading correctly, you want to transform your array from simple values to key-value pairs of 'val'->number. array_map is a concise way of doing this sort of transformation.
$array = array("v1", "v2", "v3", "v4");
$arr = array_map(function($v) { return array('val'=>$v); }, $array);
print_r($arr);
While it doesn't matter in this case, array_map also has the handy feature of preserving your keys, in case that is desired.
Note that you can also provide a named function to array_map, instead of providing the implementation inline, which can be nice in the event that your transform method gets more complicated. More on array_map here.

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