Php convert multidimensional array to single array [duplicate] - php

This question already has answers here:
How to Flatten a Multidimensional Array?
(31 answers)
Closed 3 years ago.
How can I convert multidimensional array into single array
Input
[["4|1","4|3","4|6"],[["4|1|2","4|1|8"],["4|3|4","4|3|9"],["4|6|5","4|6|12"]]]
How can I convert above input as below ?
["4|1","4|3","4|6","4|1|2","4|1|8","4|3|4","4|3|9","4|6|5","4|6|12"]

I see you want to flatten an array to 1-D. Here is recursive iterator class you can use,
$arr = [["4|1","4|3","4|6"],[["4|1|2","4|1|8"],["4|3|4","4|3|9"],["4|6|5","4|6|12"]]];
$iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($arr));
$result = [];
foreach($iterator as $v) {
$result[] = $v;
}
print_r($result);
RecursiveArrayIterator - This iterator allows to unset and modify values and keys while iterating over Arrays and Objects in the same way as the ArrayIterator. Additionally, it is possible to iterate over the current iterator entry.
Ref.
Demo
Solution 2:-
$arr = [["4|1","4|3","4|6"],[["4|1|2","4|1|8"],["4|3|4","4|3|9"],["4|6|5","4|6|12"]]];
array_walk_recursive($arr, function($v) use(&$result){
$result[] = $v;
});
print_r($result);
Demo
Output:-
Array
(
[0] => 4|1
[1] => 4|3
[2] => 4|6
[3] => 4|1|2
[4] => 4|1|8
[5] => 4|3|4
[6] => 4|3|9
[7] => 4|6|5
[8] => 4|6|12
)

You can use array_merge().
$arrays = [["4|1","4|3","4|6"],[["4|1|2","4|1|8"],["4|3|4","4|3|9"],["4|6|5","4|6|12"]]]
$arrayMerge = []
foreach($arrays as $array)
{
$arrayMerge = array_merge($arrayMerge, $array)
}
For more info: https://www.php.net/manual/es/function.array-merge.php

Try this solution. I have used a couple of foreach loops to make it simple.
<?php
$array = [["4|1","4|3","4|6"],[["4|1|2","4|1|8"],["4|3|4","4|3|9"],["4|6|5","4|6|12"]]];
foreach ($array as $key => $value) {
if($key == 0)
{
foreach ($value as $key => $v) {
$new_array[] = $v;
}
}
else
{
foreach ($value as $key => $s_value) {
foreach ($s_value as $key => $s) {
$new_array[] = $s;
}
}
}
}
print_r($new_array);
?>
Here is the live demo for you.

Use array_walk_recursive, check Demo
$result = [];
$multidimension_array = [["4|1","4|3","4|6"],[["4|1|2","4|1|8"],["4|3|4","4|3|9"],["4|6|5","4|6|12"]]];
array_walk_recursive($multidimension_array, function($v) use (&$result) { $result[] = $v; });
print_r($result);

Related

How can I call particular array value of array in php?

I'm getting below output as an array.
$array =
Array
(
[12] => Array
(
[1] => Array
(
[14] => Array
(
[0] => Array
(
[name] => Avaya Implementation Services
[service_id] => 14
[ser_type_id] => 1
[service_desc] =>Avaya Implementation Servic
)
)
)
)
);
I want to print only service_desc array value. and I don't want call like $array[12][1][14][0]['service_desc'];
How can I call particular service_desc array value of the array?
As you mentioned that you don't want to call it as $array[12][1][14][0]['service_desc'] you can use extract function which will create variables from your array,
extract($array[12][1][14][0]);
echo $service_desc;
And then you can use your particular key such as service_desc as variable.
You can try this function: (Please optimize as per your requirements)
$arr ="<YOUR ARRAY>";
$val = "service_desc";
echo removekey($arr, $val);
function removekey($arr, $val) {
$return = array();
foreach ($arr as $k => $v) {
if (is_array($v) && $k !== $val) {
removekey($v, $val);
continue;
}
if ($k == $val) {
echo ($arr[$k]);
die;
}
$return[$k] = $v;
}
return $return;
}
You can use array_walk_rescursive to frame a single dimensional array of matching keys:
DEMO
<?php
$array[12][1][14][0]['service_desc'] = 'Avaya Implementation Servic';
$array[12][1][14][0]['service'] = 'dsfasf';
$array[12][1][114][0]['service_desc'] = 'Avaya Implementation Servicasdfdsf';
$searchKey = 'service_desc';
$desiredValues = [];
array_walk_recursive($array, function ($v, $k) use ($searchKey, &$desiredValues) {
if ($k === $searchKey) {
$desiredValues[] = $v;
}
});
print_r($desiredValues);
So this will yield:
Array
(
[0] => Avaya Implementation Servic
[1] => Avaya Implementation Servicasdfdsf
)
You might use the array_walk_recursive function.
array_walk_recursive($array, function ($val, $key) {
if ($key == 'service_desc') print_r($val);
} );
Instead of the print_r statement, you can collect your data into another structure, which you convey using the use statement, or with the $userdata additional parameter (see http://www.php.net/manual/en/function.array-walk-recursive.php ).
$results = array();
array_walk_recursive($array, function ($val, $key) use (&$results) {
if ($key == 'service_desc') {
$results []= $val;
}
} );
Pay extra care to the & in front of the use (&$results) otherwise your array of results will be considered immutable inside the callback (i.e. all changes discarded).
Convert multidimensional array to single array using iterator_to_array
REF: http://php.net/manual/en/function.iterator-to-array.php
$service_desc= iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($your_array)), 0);
print_r($service_desc);
Result:
Array
(
[name] => Avaya Implementation Services
[service_id] => 14
[ser_type_id] => 1
[service_desc] =>Avaya Implementation Servic
)

Get only Numeric values from Array in PHP

I have an array that looks something like this:
Array (
[0] => Array ( [country_percentage] => 5 %North America )
[1] => Array ( [country_percentage] => 0 %Latin America )
)
I want only numeric values from above array. I want my final array like this
Array (
[0] => Array ( [country_percentage] => 5)
[1] => Array ( [country_percentage] => 0)
)
How I achieve this using PHP?? Thanks in advance...
When the number is in first position you can int cast it like so:
$newArray = [];
foreach($array => $value) {
$newArray[] = (int)$value;
}
I guess you can loop the 2 dimensional array and use a preg_replace, i.e.:
for($i=0; $i < count($arrays); $i++){
$arrays[$i]['country_percentage'] = preg_replace( '/[^\d]/', '', $arrays[$i]['country_percentage'] );
}
Ideone Demo
Update Based on your comment:
for($i=0; $i < count($arrays); $i++){
if( preg_match( '/North America/', $arrays[$i]['country_percentage'] )){
echo preg_replace( '/[^\d]/', '', $arrays[$i]['country_percentage'] );
}
}
Try this:
$arr = array(array('country_percentage' => '5 %North America'),array("country_percentage"=>"0 %Latin America"));
$result = array();
foreach($arr as $array) {
$int = filter_var($array['country_percentage'], FILTER_SANITIZE_NUMBER_INT);
$result[] = array('country_percentage' => $int);
}
Try this one:-
$arr =[['country_percentage' => '5 %North America'],
['country_percentage' => '0 %Latin America']];
$res = [];
foreach ($arr as $key => $val) {
$res[]['country_percentage'] = (int)$val['country_percentage'];
}
echo '<pre>'; print_r($res);
output:-
Array
(
[0] => Array
(
[country_percentage] => 5
)
[1] => Array
(
[country_percentage] => 0
)
)
You can use array_walk_recursive to do away with the loop,
passing the first parameter of the callback as a reference to modify the initial array value.
Then just apply either filter_var or intval as already mentioned the other answers.
$array = [
["country_percentage" => "5 %North America"],
["country_percentage" => "0 %Latin America"]
];
array_walk_recursive($array, function(&$value,$key){
$value = filter_var($value,FILTER_SANITIZE_NUMBER_INT);
// or
$value = intval($value);
});
print_r($array);
Will output
Array
(
[0] => Array
(
[country_percentage] => 5
)
[1] => Array
(
[country_percentage] => 0
)
)
You could get all nemeric values by looping through the array. However I don't think this is the most efficient and good looking answer, I'll post it anyways.
// Array to hold just the numbers
$newArray = array();
// Loop through array
foreach ($array as $key => $value) {
// Check if the value is numeric
if (is_numeric($value)) {
$newArray[$key] = $value;
}
}
I missunderstood your question.
$newArray = array();
foreach ($array as $key => $value) {
foreach ($value as $subkey => $subvalue) {
$subvalue = trim(current(explode('%', $subvalue)));
$newArray[$key] = array($subkey => $subvalue);
}
}
If you want all but numeric values :
$array[] = array("country_percentage"=>"5 %North America");
$array[] = array("country_percentage"=>"3 %Latin America");
$newArray = [];
foreach ($array as $arr){
foreach($arr as $key1=>$arr1) {
$newArray[][$key1] = intval($arr1);
}
}
echo "<pre>";
print_R($newArray);
This is kind of a ghetto method to doing it cause I love using not as many pre made functions as possible. But this should work for you :D
$array = array('jack', 2, 5, 'gday!');
$new = array();
foreach ($array as $item) {
// IF Is numeric (each item from the array) will insert into new array called $new.
if (is_numeric($item)) { array_push($new, $item); }
}

How to get common values from 4 multidimensional arrays using array_intersect

i am stuck at this stage of my project.
i am trying to get common values from four multidimensional arrays using array_intersect. can anyone help me with this issue ?
here are all four array:
$arr=array(array(8159),array(8140),array(8134),array( 8168),array(8178),array( 8182),array( 8183));
$arr1=array(array(8159),array(8140),array(8134),array(8165),array(8166),array(8167),array( 8168));
$arr2=array(array(566),array(265),array(8134),array(655),array(8166),array(665),array( 8168),array(656),array( 989),array( 989));
$arr3=array(array(8159),array(8140),array(8134),array(8165),array(8166),array(8167),array( 8168));
$res= array_intersect($arr,$arr1,$arr2,$arr3);
print_r($res);
If subarray contain one element always you could chage that value using array_map and current function.
$arr=array(array(8159),array(8140),array(8134),array( 8168),array(8178),array( 8182),array( 8183));
$arr1=array(array(8159),array(8140),array(8134),array(8165),array(8166),array(8167),array( 8168));
$arr2=array(array(566),array(265),array(8134),array(655),array(8166),array(665),array( 8168),array(656),array( 989),array( 989));
$arr3=array(array(8159),array(8140),array(8134),array(8165),array(8166),array(8167),array( 8168));
$arr = array_map('current', $arr); // getting first value of subarray
$arr1 = array_map('current', $arr1);
$arr2 = array_map('current', $arr2);
$arr3 = array_map('current', $arr3);
print_r($arr3);
// Array
// (
// [0] => 8159
// [1] => 8140
// [2] => 8134
// [3] => 8165
// [4] => 8166
// [5] => 8167
// [6] => 8168
// )
$res= array_intersect($arr,$arr1,$arr2,$arr3);
print_r($res);
// Array
// (
// [2] => 8134
// [3] => 8168
// )
Please check this
$arr=array(array(8159),array(8140),array(8134),array( 8168),array(8178),array( 8182),array( 8183));
$arr1=array(array(8159),array(8140),array(8134),array(8165),array(8166),array(8167),array( 8168));
$arr2=array(array(566),array(265),array(8134),array(655),array(8166),array(665),array( 8168),array(656),array( 989),array( 989));
$arr3=array(array(8159),array(8140),array(8134),array(8165),array(8166),array(8167),array( 8168));
foreach($arr as $value)
{
$a1[] = $value[0];
}
foreach($arr1 as $value)
{
$a2[] = $value[0];
}
foreach($arr2 as $value)
{
$a3[] = $value[0];
}
foreach($arr3 as $value)
{
$a4[] = $value[0];
}
$res= array_intersect($a1,$a2,$a3,$a4);
print_r($res);

Simplify a nested array into a single level array [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How to Flatten a Multidimensional Array?
Let's say I have an array like this:
array (
1 =>
array (
2 =>
array (
16 =>
array (
18 =>
array (
),
),
17 =>
array (
),
),
),
14 =>
array (
15 =>
array (
),
),
)
How would I go about tranforming it into array like this?
array(1,2,16,18,17,14,15);
Sorry for the closevote. Didnt pay proper attention about you wanting the keys. Solution below:
$iterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator($arr),
RecursiveIteratorIterator::SELF_FIRST);
$keys = array();
and then either
$keys = array();
foreach($iterator as $key => $val) {
$keys[] = $key;
}
or with the iterator instance directly
$keys = array();
for($iterator->rewind(); $iterator->valid(); $iterator->next()) {
$keys[] = $iterator->key();
}
or more complicated than necessary
iterator_apply($iterator, function(Iterator $iterator) use (&$keys) {
$keys[] = $iterator->key();
return TRUE;
}, array($iterator));
gives
Array
(
[0] => 1
[1] => 2
[2] => 16
[3] => 18
[4] => 17
[5] => 14
[6] => 15
)
how about some recursion
$result = array();
function walkthrough($arr){
$keys = array_keys($arr);
array_push($result, $keys);
foreach ($keys as $key)
{
if (is_array($arr[$key]))
walkthrough($arr[$key]);
else
array_push($result,$arr[$key]);
}
return $result;
}
walkthrouth($your_arr);
P.S.:Code can be bugged, but you've got an idea :)
function flattenArray($array) {
$arrayValues = array();
foreach (new RecursiveIteratorIterator( new RecursiveArrayIterator($array)) as $val) {
$arrayValues[] = $val;
}
return $arrayValues;
} // function flattenArrayIndexed()
If we consider the nested array as a tree structure, you can apply depth first traversal to convert it into a list. That is, into a single array you desire.
I have searched all similar questions and it seems there is no way without a recursion that would keep the keys order intact.
So I just went with classic recursion:
function getArrayKeysRecursive(array $theArray)
{
$aArrayKeys = array();
foreach ($theArray as $k=>$v) {
if (is_array($v)) {
$aArrayKeys = array_merge($aArrayKeys, array($k), getArrayKeysRecursive($v));
} else {
$aArrayKeys = array_merge($aArrayKeys, array($k));
}
}
return $aArrayKeys;
}

PHP: Turning multidimensional arrays to single dimension arrays

Basically my app is interacting with a web service that sends back a weird multidimensional array such as:
Array
(
[0] => Array
(
[Price] => 1
)
[1] => Array
(
[Size] => 7
)
[2] => Array
(
[Type] => 2
)
)
That's not a problem, but the problem is that the service keeps changing the index of those items, so in the next array the Price could be at 1 instead of 0.
How do I effeciently transform arrays like this into a single dimension array so I can access the variables through $var['Size'] instead of $var[1]['Size']?
Appreciate your help
$result = call_user_func_array('array_merge', $array);
Like this:
$result = array();
foreach($array as $inner) {
$result[key($inner)] = current($inner);
}
The $result array would now look like this:
Array
(
[Price] => 1
[Size] => 7
[Type] => 2
)
I am using laravel's helper: http://laravel.com/api/source-function-array_flatten.html#179-192
function array_flatten($array)
{
$return = array();
array_walk_recursive($array, function($x) use (&$return) { $return[] = $x; });
return $return;
}
function flattenArray($input, $maxdepth = NULL, $depth = 0)
{
if(!is_array($input)){
return $input;
}
$depth++;
$array = array();
foreach($input as $key=>$value){
if(($depth <= $maxdepth or is_null($maxdepth)) && is_array($value)){
$array = array_merge($array, flattenArray($value, $maxdepth, $depth));
} else {
array_push($array, $value);
// or $array[$key] = $value;
}
}
return $array;
}
Consider $mArray as multidimensional array and $sArray as single dimensional array this code will ignore the parent array
function flatten_array($mArray) {
$sArray = array();
foreach ($mArray as $row) {
if ( !(is_array($row)) ) {
if($sArray[] = $row){
}
} else {
$sArray = array_merge($sArray,flatten_array($row));
}
}
return $sArray;
}
I think i found best solution to this : array_walk_recursive($yourOLDmultidimarray, function ($item, $key) {
//echo "$key holds $item\n";
$yourNEWarray[]=$item;
});
If you use php >= 5.6, you may use array unpacking (it's much faster):
$result = array_merge(...$array);
See wiki.php.net on unpacking

Categories