Convert a multidimensional array into simpler form [duplicate] - php

This question already has answers here:
Turning multidimensional array into one-dimensional array [duplicate]
(11 answers)
Closed 7 years ago.
I have an array as shown below,
How to convert the above array1 into array2 form?
array1
Array
(
[0] => Array
(
[0] => 500 GB
)
[1] => Array
(
[0] => 100 GB
)
)
array2
Array
(
[0] => 500 GB
[1] => 100 GB
)

$yourArray = [[0 => '500 GB'], [0 => '100 GB'], [1 => '200 GB']];
$result = array_filter(
array_map(
function($element) {
if (isset($element[0])) {
return $element[0];
}
return;
},
$yourArray
),
function($element) {
return $element !== null;
}
);
echo var_dump($result); // array(2) { [0]=> string(6) "500 GB" [1]=> string(6) "100 GB" }
This will work only with php >= 5.4 (because of array short syntax). If you're running on older versione, just substitute [] with array()
Explaination
array_filter is used to exclude certain values from an array (by using a callback function). In this case, NULL values that you get from array_map.
array_map is used to apply a function to "transform" your array. In particular it applies a function to each array element and returns that element after function application.

Related

How to partly remove from strings in Array [duplicate]

This question already has answers here:
How can I remove the file extension from each string in a PHP array?
(4 answers)
Closed 3 years ago.
I was wondering if there is any basic solution to remove the endings of all strings in an array?
I could do it with a foreach etc. but I'm looking for something somewhat smaller in code.
For example, converting this:
Array ( [0] => test1.csv [1] => test2.csv [2] => test3.csv )
To this:
Array ( [0] => test1 [1] => test2 [2] => test3 )
try this :
<?php
$arr = array ('test1.csv', 'test2.csv', 'test3.csv' );
array_walk($arr, function(&$val){
$val = str_replace('.csv','',$val);
return $val;
});
You can use basename() which will remove extensions or unwanted characters from filenames.
$files = ['test1.csv', 'test2.csv', 'test3.csv'];
$filesWithoutExt = array_map(function($e) { return basename($e, '.csv'); }, $files);
var_dump($filesWithoutExt);
array(3) {
[0] =>
string(5) "test1"
[1] =>
string(5) "test2"
[2] =>
string(5) "test3"
}
Another array_map using pathinfo to return the filename (PATHINFO_FILENAME basename without any extension):
$array = array_map(function($v) { return pathinfo($v, PATHINFO_FILENAME); }, $array);

array_column with an array of objects [duplicate]

This question already has answers here:
PHP. Is it possible to use array_column with an array of objects
(5 answers)
Closed 6 years ago.
TLDR; My question is different from PHP. Is it possible to use array_column with an array of objects. I want to only change the keys within the array and keep the objects, not having the objects' values stored in a separate array like the given answer.
I would like to set the keys, of an array with objects, to a value of the object. So this array:
$array = Array
(
[0] => stdClass Object
(
[id] = 12234
[value] = some value
)
[1] => stdClass Object
(
[id] = 12994
[value] = some value
)
)
Should become:
$array = Array
(
[12234] => stdClass Object
(
[id] = 12234
[value] = some value
)
[12994] => stdClass Object
(
[id] = 12994
[value] = some value
)
)
Now I could loop over the array, but I would prefer a more cleaner solution. I thought this should work:
$newArray = array_column($array, null, 'id');
The only problem is I'm having an array of objects instead of an array of arrays and I'm not using PHP7 yet. Now I found a similar question over here
PHP. Is it possible to use array_column with an array of objects
But the thing is it doesn't return what I expected. Cause this:
$newArray = array_map(function($o) {
return is_object($o) ? $o->id : $o['id'];
}, $array);
Returns
Array
(
[0] => 12234
[1] => 12994
)
Anyone who knows a clean solution (so without a for or foreach loop) for this?
$array = array_combine(array_map(function ($o) { return $o->id; }, $array), $array);
Whether this is really a lot better than a simple foreach loop, aside from "but, but, functional programming...!", is debatable.
// your data
$array = array(
(object) array(
"id" => "12234",
"value" => "some value",
),
(object) array(
"id" => "12235",
"value" => "some value",
),
(object) array(
"id" => "12236",
"value" => "some value",
),
);
// let's see what we have
print_r($array);
// here comes the magic ;-)
function key_flip_array($array, $keyname){
$keys = array_map(function($item, $keyname){
return (is_object($item) && isset($item->{$keyname}) ? $item->{$keyname} : (is_array($item) && isset($item[$keyname]) ? $item[$keyname] : null));
}, $array, array_fill(0, count($array), $keyname));
return array_combine($keys, $array);
}
$array = key_flip_array($array, "id");
// i hope this is what you wish to see
print_r($array);

How to remove duplicate from an Array and sort it? [duplicate]

This question already has answers here:
How to remove duplicate values from a multi-dimensional array in PHP
(18 answers)
Closed 8 years ago.
I have array A :
Input:
A ={2,3,2,{1},3,2,{0},3,2,0,11,7,9,{2}}
I want output to be Array B
Output:
B={0,1,2,3,7,9,11}
How can i remove the duplicate values and sort them ascending with PHP?
if you have:
$a = array(2,3,2,1,3,2,0,3,2,0,11,7,9,2);
you can use array_unique() to remove duplicates:
$a = array_unique($a);
and then use asort() to sort the array values:
asort($a);
//Try this out...
$array = array(2,3,2,(1),3,2,(0),3,2,0,11,7,9,(2));
$array_u = array_unique($array);
sort($array_u);
print_r($array_u);
Sample output
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 7
[5] => 9
[6] => 11
)
First step: flattern
function flatten(array $array) {
$return = array();
array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
return $return;
}
then using asort and array_unique you can remove duplicates and sort ascendent.
$result = array_unique(flattern($array));
asort($result);
Sources:
How to Flatten a Multidimensional Array?

PHP: remove empty array strings in multidimensional array [duplicate]

This question already has answers here:
How to remove empty values from multidimensional array in PHP?
(9 answers)
Closed 9 years ago.
I have this array:
$aryMain = array(array('hello','bye'), array('',''),array('',''));
It is formed by reading a csv file and the array('','') are the empty rows at the end of the file.
How can I remove them?
I've tried:
$aryMain = array_filter($aryMain);
But it is not working :(
Thanks a lot!
To add to Rikesh's answer:
<?php
$aryMain = array(array('hello','bye'), array('',''),array('',''));
$aryMain = array_filter(array_map('array_filter', $aryMain));
print_r($aryMain);
?>
Sticking his code into another array_filter will get rid of the entire arrays themselves.
Array
(
[0] => Array
(
[0] => hello
[1] => bye
)
)
Compared to:
$aryMain = array_map('array_filter', $aryMain);
Array
(
[0] => Array
(
[0] => hello
[1] => bye
)
[1] => Array
(
)
[2] => Array
(
)
)
Use array_map along with array_filter,
$array = array_filter(array_map('array_filter', $array));
Or just create a array_filter_recursive function
function array_filter_recursive($input)
{
foreach ($input as &$value)
{
if (is_array($value))
{
$value = array_filter_recursive($value);
}
}
return array_filter($input);
}
DEMO.
Note: that this will remove items comprising '0' (i.e. string with a numeral zero). Just pass 'strlen' as a second parameter to keep 0
Apply array_filter() on the main array and then once more on the inner elements:
$aryMain = array_filter($aryMain, function($item) {
return array_filter($item, 'strlen');
});
The inner array_filter() specifically uses strlen() to determine whether the element is empty; otherwise it would remove '0' as well.
To determine the emptiness of an array you could also use array_reduce():
array_filter($aryMain, function($item) {
return array_reduce($item, function(&$res, $item) {
return $res + strlen($item);
}, 0);
});
Whether that's more efficient is arguable, but it should save some memory :)

count element in array? [duplicate]

This question already has answers here:
Working with arrays in php
(4 answers)
Closed 3 years ago.
I have an Array like this (when I print_r). How can I sum all elements in this Array?
In this example, the sum is 0+1=1
Array ( [0] => Array ( [0] => 0 )
[1] => Array ( [0] => 1 ) )
Take a look at the 'array_reduce' function: array_reduce: http://nl.php.net/manual/en/function.array-reduce.php
Taken from the documentation:
function rsum($v, $w)
{
$v += $w;
return $v;
}
$sum = array_reduce($a, "rsum");

Categories