Related
I have a multidimensional array that can have any depth. What im trying to do is to filter the whole path based on dynamic keys and create a new array of it.
Example of the array
$originalArray = [
"title" => "BACKPACK MULTICOLOUR",
"description" => "description here",
"images" => [
[
"id" => 12323123123,
"width" => 635,
"height" => 560,
"src" => "https://example.com",
"variant_ids": [32694976315473, 32863017926737],
],
[
"id" => 4365656656565,
"width" => 635,
"height" => 560,
"src" => "https://example.com",
"variant_ids": [32694976315473, 32863017926737],
]
],
"price" => [
"normal" => 11.00,
"discount" => [
"gold_members" => 9.00,
"silver_members" => 10.00,
"bronze_members" => null
]
]
];
Example how the output should look like with the key "title, width, height, gold_members" filtered out. Only keys from the end of the array tree should be valid, so nothing must happen when images is in the filter
$newArray = [
"title" => "BACKPACK MULTICOLOUR",
"images" => [
[
"width" => 635,
"height" => 560,
],
[
"width" => 635,
"height" => 560,
]
],
"price" => [
"discount" => [
"gold_members" => 9.00,
]
]
];
I guess that i should create a function that loop through each element and when it is an associative array, it should call itself again
Because the filtered paths are unknown i cannot make a hardcoded setter like this:
$newArray["images"][0]["width"] = 635
The following filter will be an example but it should basically be dynamic
example what i have now:
$newArray = handleArray($originalArray);
handleArray($array)
{
$filter = ["title", "width", "height", "gold_members"];
foreach ($array as $key => $value) {
if (is_array($value)) {
$this->handleArray($value);
} else {
if (in_array($key, $filter)) {
// put this full path in the new array
}
}
}
}
[Solved] Update:
I solved my problem thanks to #trincot
I used his code and added an extra check to add an array with multiple values to the new array
My code to solve the issue:
<?php
function isListOfValues($array) {
$listOfArrays = [];
foreach ($array as $key => $value) {
$listOfArrays[] = ! is_array($value) && is_int($key);
}
return array_sum($listOfArrays) === count($listOfArrays);
}
function filterKeysRecursive(&$arr, &$keep) {
$result = [];
foreach ($arr as $key => $value) {
if (is_array($value) && ! isListOfValues($value)) {
$value = filterKeysRecursive($value, $keep);
if (count($value)) {
$result[$key] = $value;
}
} else if (array_key_exists($key, $keep)) {
$result[$key] = $value;
}
}
return $result;
}
$keep = array_flip(["title", "width", "height", "gold_members"]);
$result = filterKeysRecursive($originalArray, $keep);
You could use a recursive function, with following logic:
base case: the value associated with a key is not an array (it is a "leaf"). In that case the new object will have that key/value only when the key is in the list of desired keys.
recursive case: the value associated with a key is an array. Apply recursion to that value. Only add the key when the returned result is not an empty array. In that case associate the filtered value to the key in the result object.
To speed up the look up in the list of keys, it is better to flip that list into an associative array.
Here is the implementation:
function filter_keys_recursive(&$arr, &$keep) {
foreach ($arr as $key => $value) {
if (is_array($value)) {
$value = filter_keys_recursive($value, $keep);
if (count($value)) $result[$key] = $value;
} else if (array_key_exists($key, $keep)) {
$result[$key] = $value;
}
}
return $result;
}
$originalArray = ["title" => "BACKPACK MULTICOLOUR","description" => "description here","images" => [["id" => 12323123123,"width" => 635,"height" => 560,"src" => "https://example.com"],["id" => 4365656656565,"width" => 635,"height" => 560,"src" => "https://example.com"]],"price" => ["normal" => 11.00,"discount" => ["gold_members" => 9.00,"silver_members" => 10.00,"bronze_members" => null]]];
$keep = array_flip(["title", "width", "height", "gold_members"]);
$result = filter_keys_recursive($originalArray, $keep);
My proposition to you is to write a custom function to transform structure from one schema to another:
function transform(array $originalArray): array {
array_walk($originalArray['images'], function (&$a, $k) {
unset($a['id']); unset($a['src']);
});
unset($originalArray['description']);
unset($originalArray['price']['normal']);
unset($originalArray['price']['discount']['silver_members']);
unset($originalArray['price']['discount']['bronze_members']);
return $originalArray;
}
var_dump(transform($originalArray));
If you are familiar with OOP I suggest you to look at how DTO works in API Platform for example and inject this idea into your code by creating custom DataTransformers where you specify which kind of structers you want to support with transformer and a method where you transform one structure to another.
Iterate over the array recursively on each key and subarray.
If the current key in the foreach is a required key in the result then:
If the value is not an array, simply assign the value
If the value is an array, iterate further down over value recursively just in case if there is any other filtering of the subarray keys that needs to be done.
If the current key in the foreach is NOT a required key in the result then:
Iterate over value recursively if it's an array in itself. This is required because there could be one of the filter keys deep down which we would need. Get the result and only include it in the current subresult if it's result is not an empty array. Else, we can skip it safely as there are no required keys down that line.
Snippet:
<?php
function filterKeys($array, $filter_keys) {
$sub_result = [];
foreach ($array as $key => $value) {
if(in_array($key, $filter_keys)){// if $key itself is present in $filter_keys
if(!is_array($value)) $sub_result[$key] = $value;
else{
$temp = filterKeys($value, $filter_keys);
$sub_result[$key] = count($temp) > 0 ? $temp : $value;
}
}else if(is_array($value)){// if $key is not present in $filter_keys - iterate over the remaining subarray for that key
$temp = filterKeys($value, $filter_keys);
if(count($temp) > 0) $sub_result[$key] = $temp;
}
}
return $sub_result;
}
$result = filterKeys($originalArray, ["title", "width", "height", "gold_members"]);
print_r($result);
Online Demo
Try this way.
$expectedKeys = ['title','images','width','height','price','gold_members'];
function removeUnexpectedKeys ($originalArray,$expectedKeys)
{
foreach ($originalArray as $key=>$value) {
if(is_array($value)) {
$originalArray[$key] = removeUnexpectedKeys($value,$expectedKeys);
if(!is_array($originalArray[$key]) or count($originalArray[$key]) == 0) {
unset($originalArray[$key]);
}
} else {
if (!in_array($key,$expectedKeys)){
unset($originalArray[$key]);
}
}
}
return $originalArray;
}
$newArray = removeUnexpectedKeys ($originalArray,$expectedKeys);
print_r($newArray);
check this on editor,
https://www.online-ide.com/vFN69waXMf
This is just in case someone else has the same question and like me did not find a suitable answer to solve it.
I had a collection that had to be filtered so the active item comes first on the collections when a certain value was passed.
Illuminate\Database\Eloquent\Collection {
0 => array:2 [
"id" => 1
"name" => "Bogan, Weissnat and Jenkins"
]
1 => array:2 [
"id" => 4
"name" => "Grady-Barrows"
]
2 => array:2 [
"id" => 7
"name" => "Howe and Sons"
]
3 => array:2 [
"id" => 3
"name" => "Macejkovic-Altenwerth"
]
]
}
Needed to move an item top based on the id which is passed by URL
$activeId = 3; // Your active item id
$collection = $collection
->sortBy('id')
->sortBy(fn($item) => $item->id !== $activeId);
This will sort your collection by id and move a specific item to the top.
(PHP7.4+ for arrow function)
You can simply sort the collection by a custom function:
use Illuminate\Support\Collection;
$data = collect([
["id" => 1, "name" => "Bogan, Weissnat and Jenkins"],
["id" => 4, "name" => "Grady-Barrows"],
["id" => 7, "name" => "Howe and Sons"],
["id" => 3, "name" => "Macejkovic-Altenwerth"],
]);
$key = "name";
$value = "Grady-Barrows";
public function moveFirst(Collection $data, string $key, mixed $value): Collection
{
return $data->sortBy(fn($v) => $v[$key] !== $value);
}
It will return false (0) for the matching entry and true (1) for the rest, so the matching entry gets put on top. Using arrow functions makes for a much simpler syntax.
This is how I did solve it.
public function moveOtherToTop($collection, $key, $item)
{
return $collection->reject(function ($value) use ($item){
return $value[$key] == $item;
})->prepend($collection->filter(function ($value) use ($item) {
return $value[$key] == $item;
})[$item]);
}
Idea came out from Laracast and Stillat article.
In case there is a better solution to this answer am open to suggestions.
I run this in Laravel 5.8
use Illuminate\Support\Collection;
function moveItemToTopCollection(Collection $collection, String $key, $value) :Collection
{
$item_to_first = null;
// Search element to top
foreach ($collection as $item) {
if ($item->$key == $value){
$item_to_first = $item;
break;
}
}
// If element not found, return original collection
if (!$item_to_first){
return $collection;
}
// Element to top, first remove of collection, then insert to top
return $collection->reject(function ($value) use ($item_to_first){
return $value == $item_to_first;
})->prepend($item_to_first);
}
You can use the prioritize method from the great spatie/laravel-collection-macros package.
This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed last month.
I have an array which is multidimensional for no reason
/* This is how my array is currently */
Array
(
[0] => Array
(
[0] => Array
(
[plan] => basic
)
[1] => Array
(
[plan] => small
)
[2] => Array
(
[plan] => novice
)
[3] => Array
(
[plan] => professional
)
[4] => Array
(
[plan] => master
)
[5] => Array
(
[plan] => promo
)
[6] => Array
(
[plan] => newplan
)
)
)
I want to convert this array into this form
/*Now, I want to simply it down to this*/
Array (
[0] => basic
[1] => small
[2] => novice
[3] => professional
[4] => master
[5] => promo
[6] => newplan
)
Any idea how to do this?
This single line would do that:
$array = array_column($array, 'plan');
The first argument is an array | The second argument is an array key.
For details, go to official documentation: https://www.php.net/manual/en/function.array-column.php.
Assuming this array may or may not be redundantly nested and you're unsure of how deep it goes, this should flatten it for you:
function array_flatten($array) {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, array_flatten($value));
}
else {
$result[$key] = $value;
}
}
return $result;
}
If you come across a multidimensional array that is pure data, like this one below, then you can use a single call to array_merge() to do the job via reflection:
$arrayMult = [ ['a','b'] , ['c', 'd'] ];
$arraySingle = call_user_func_array('array_merge', $arrayMult);
// $arraySingle is now = ['a','b', 'c', 'd'];
Just assign it to it's own first element:
$array = $array[0];
For this particular case, this'll do:
$array = array_map('current', $array[0]);
It's basically the exact same question is this one, look at some answers there: PHP array merge from unknown number of parameters.
$singleArray = array();
foreach ($multiDimensionalArray as $key => $value){
$singleArray[$key] = $value['plan'];
}
this is best way to create a array from multiDimensionalArray array.
thanks
Problem array:
array:2 [▼
0 => array:3 [▼
0 => array:4 [▼
"id" => 8
"name" => "Veggie Burger"
"image" => ""
"Category_type" => "product"
]
1 => array:4 [▼
"id" => 9
"name" => "Veggie Pitta"
"image" => ""
"Category_type" => "product"
]
2 => array:4 [▼
"id" => 10
"name" => "Veggie Wrap"
"image" => ""
"Category_type" => "product"
]
]
1 => array:2 [▼
0 => array:4 [▼
"id" => 18
"name" => "Cans 330ml"
"image" => ""
"Category_type" => "product"
]
1 => array:4 [▼
"id" => 19
"name" => "Bottles 1.5 Ltr"
"image" => ""
"Category_type" => "product"
]
]
]
Solution array:
array:5 [▼
0 => array:4 [▼
"id" => 8
"name" => "Veggie Burger"
"image" => ""
"Category_type" => "product"
]
1 => array:4 [▼
"id" => 9
"name" => "Veggie Pitta"
"image" => ""
"Category_type" => "product"
]
2 => array:4 [▼
"id" => 10
"name" => "Veggie Wrap"
"image" => ""
"Category_type" => "product"
]
3 => array:4 [▼
"id" => 18
"name" => "Cans 330ml"
"image" => ""
"Category_type" => "product"
]
4 => array:4 [▼
"id" => 19
"name" => "Bottles 1.5 Ltr"
"image" => ""
"Category_type" => "product"
]
]
Write this code and get your solution , $subcate is your multi dimensional array.
$singleArrayForCategory = array_reduce($subcate, 'array_merge', array());
none of answers helped me, in case when I had several levels of nested arrays. the solution is almost same as #AlienWebguy already did, but with tiny difference.
function nestedToSingle(array $array)
{
$singleDimArray = [];
foreach ($array as $item) {
if (is_array($item)) {
$singleDimArray = array_merge($singleDimArray, nestedToSingle($item));
} else {
$singleDimArray[] = $item;
}
}
return $singleDimArray;
}
test example
$array = [
'first',
'second',
[
'third',
'fourth',
],
'fifth',
[
'sixth',
[
'seventh',
'eighth',
[
'ninth',
[
[
'tenth'
]
]
],
'eleventh'
]
],
'twelfth'
];
$array = nestedToSingle($array);
print_r($array);
//output
array:12 [
0 => "first"
1 => "second"
2 => "third"
3 => "fourth"
4 => "fifth"
5 => "sixth"
6 => "seventh"
7 => "eighth"
8 => "ninth"
9 => "tenth"
10 => "eleventh"
11 => "twelfth"
]
You can do it just using a loop.
$singleArray = array();
foreach ($multiDimensionalArray as $key => $value){
$singleArray[$key] = $value['plan'];
}
Your sample array has 3 levels. Because the first level has only [0], you can hardcode your access into it and avoid an extra function/construct call.
(Code Demos)
array_walk_recursive() is handy and versatile, but for this task may be overkill and certainly a bit more convoluted in terms of readability.
array_walk_recursive($array, function($leafvalue)use(&$flat){$flat[] = $leafvalue;});
var_export($flat);
If this was my code, I'd be using array_column() because it is direct and speaks literally about the action being performed.
var_export(array_column($array[0], 'plan'));
Of course a couple of `foreach() loops will perform very efficiently because language constructs generally perform more efficiently than function calls.
foreach ($array[0] as $plans) {
foreach ($plans as $value) {
$flat[] = $value;
}
}
var_export($flat);
Finally, as a funky alternative (which I can't imagine actually putting to use unless I was writing code for someone whom I didn't care for) I'll offer an array_merge_recursive() call with a splat operator (...).
var_export(array_merge_recursive(...$array[0])['plan']);
Despite that array_column will work nice here, in case you need to flatten any array no matter of it's internal structure you can use this array library to achieve it without ease:
$flattened = Arr::flatten($array);
which will produce exactly the array you want.
This simple code you can use
$array = array_column($array, 'value', 'key');
Recently I've been using AlienWebguy's array_flatten function but it gave me a problem that was very hard to find the cause of.
array_merge causes problems, and this isn't the first time that I've made problems with it either. If you have the same array keys in one inner array that you do in another, then the later values will overwrite the previous ones in the merged array.
Here's a different version of array_flatten without using array_merge:
function array_flatten($array) {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$arrayList=array_flatten($value);
foreach ($arrayList as $listItem) {
$result[] = $listItem;
}
}
else {
$result[$key] = $value;
}
}
return $result;
}
There is an error in most voted answer. Here is the correct version.
function array_flatten($array) {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, array_flatten($value));
}
else {
$result[] = $value;
}
}
return $result;
}
The difference is on the line $result[] = $value;
Original answer was $result[$key] = $value;
The $key index is incorrect after flattering any array in the cycle.
Following this pattern
$input = array(10, 20, array(30, 40), array('key1' => '50', 'key2'=>array(60), 70));
Call the function :
echo "<pre>";print_r(flatten_array($input, $output=null));
Function Declaration :
function flatten_array($input, $output=null) {
if($input == null) return null;
if($output == null) $output = array();
foreach($input as $value) {
if(is_array($value)) {
$output = flatten_array($value, $output);
} else {
array_push($output, $value);
}
}
return $output;
}
I've written a complement to the accepted answer. In case someone, like myself need a prefixed version of the keys, this can be helpful.
Array
(
[root] => Array
(
[url] => http://localhost/misc/markia
)
)
Array
(
[root.url] => http://localhost/misc/markia
)
<?php
function flattenOptions($array, $old = '') {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, flattenOptions($value, $key));
}
else {
$result[$old . '.' . $key] = $value;
}
}
return $result;
}
I had come across the same requirement to flatter multidimensional array into single dimensional array than search value using text in key. here is my code
$data = '{
"json_data": [{
"downtime": true,
"pfix": {
"max": 100,
"threshold": 880
},
"ints": {
"int": [{
"rle": "pri",
"device": "laptop",
"int": "Ether3",
"ip": "127.0.0.3"
}],
"eth": {
"lan": 57
}
}
},
{
"downtime": false,
"lsi": "987654",
"pfix": {
"min": 10000,
"threshold": 890
},
"mana": {
"mode": "NONE"
},
"ints": {
"int": [{
"rle": "sre",
"device": "desk",
"int": "Ten",
"ip": "1.1.1.1",
"UF": true
}],
"ethernet": {
"lan": 2
}
}
}
]
}
';
$data = json_decode($data,true);
$stack = &$data;
$separator = '.';
$toc = array();
while ($stack) {
list($key, $value) = each($stack);
unset($stack[$key]);
if (is_array($value)) {
$build = array($key => ''); # numbering without a title.
foreach ($value as $subKey => $node)
$build[$key . $separator . $subKey] = $node;
$stack = $build + $stack;
continue;
}
if(!is_numeric($key)){
$toc[$key] = $value;
}
}
echo '<pre/>';
print_r($toc);
My output:
Array
(
[json_data] =>
[json_data.0] =>
[json_data.0.downtime] => 1
[json_data.0.pfix] =>
[json_data.0.pfix.max] => 100
[json_data.0.pfix.threshold] => 880
[json_data.0.ints] =>
[json_data.0.ints.int] =>
[json_data.0.ints.int.0] =>
[json_data.0.ints.int.0.rle] => pri
[json_data.0.ints.int.0.device] => laptop
[json_data.0.ints.int.0.int] => Ether3
[json_data.0.ints.int.0.ip] => 127.0.0.3
[json_data.0.ints.eth] =>
[json_data.0.ints.eth.lan] => 57
[json_data.1] =>
[json_data.1.downtime] =>
[json_data.1.lsi] => 987654
[json_data.1.pfix] =>
[json_data.1.pfix.min] => 10000
[json_data.1.pfix.threshold] => 890
[json_data.1.mana] =>
[json_data.1.mana.mode] => NONE
[json_data.1.ints] =>
[json_data.1.ints.int] =>
[json_data.1.ints.int.0] =>
[json_data.1.ints.int.0.rle] => sre
[json_data.1.ints.int.0.device] => desk
[json_data.1.ints.int.0.int] => Ten
[json_data.1.ints.int.0.ip] => 1.1.1.1
[json_data.1.ints.int.0.UF] => 1
[json_data.1.ints.ethernet] =>
[json_data.1.ints.ethernet.lan] => 2
)
This is my contribuition
function arrayUnica($array, $prefix = "")
{
if (!is_array($array)) {
return false;
}
$new_array = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
$key = is_int($key) ? $prefix . $key . "-" : $key . "_";
$new_array = array_merge($new_array, arrayUnica($value, $key));
} else {
$new_array[$prefix . $key] = $value;
}
}
return $new_array;
}
Hope this will helpful for you,
$array= 'YOUR_MULTIDIMENSIONAL_ARRAY';
$arr=[];
array_walk_recursive($array, function($k){global $arr; $arr[]=$k;});
print_r($arr);
I have done this with OOP style
$res=[1=>[2,3,7,8,19],3=>[4,12],2=>[5,9],5=>6,7=>[10,13],10=>[11,18],8=>[14,20],12=>15,6=>[16,17]];
class MultiToSingle{
public $result=[];
public function __construct($array){
if(!is_array($array)){
echo "Give a array";
}
foreach($array as $key => $value){
if(is_array($value)){
for($i=0;$i<count($value);$i++){
$this->result[]=$value[$i];
}
}else{
$this->result[]=$value;
}
}
}
}
$obj= new MultiToSingle($res);
$array=$obj->result;
print_r($array);
Multi dimensional array to single array with one line code !!!
Enjoy the code.
$array=[1=>[2,5=>[4,2],[7,8=>[3,6]],5],4];
$arr=[];
array_walk_recursive($array, function($k){global $arr; $arr[]=$k;});
print_r($arr);
...Enjoy the code.
Try this it works for me:
$newArray = array();
foreach($operator_call_logs as $array) {
foreach($array as $k=>$v) {
$newArray[$k] = $v;
}
}
Save this as a php file, simply import and use single_array() function
<?php
$GLOBALS['single_array']=[];
function array_conveter($array_list){
if(is_array($array_list)){
foreach($array_list as $array_ele){
if(is_array($array_ele)){
array_conveter($array_ele);
}else{
array_push($GLOBALS['single_array'],$array_ele);
}
}
}else{
array_push($GLOBALS['single_array'],$array_list);
}
}
function single_array($mix){
foreach($mix as $single){
array_conveter($single);
}return $GLOBALS['single_array'];
$GLOBALS['single_array']=[];
}
/* Example convert your multi array to single */
$mix_array=[3,4,5,[4,6,6,7],'abc'];
print_r(single_array($mix_array));
?>
if use php version 7.4 and above
$users = [
[
'Ahmed',
'Mohammed',
],
[
'Saeed',
'Rami',
'Haider',
],
];
$admin = array_merge(...$users);
I am trying to search an array for an element (in this case 'electronic'), then return the nested value.
The array that I am working with
array:2 [▼
0 => array:2 [▼
"value" => "0241-6230"
"type" => "print"
]
1 => array:2 [▼
"value" => "2339-1623"
"type" => "electronic"
]
]
Below is the code I'm using.
<?php
$this->doi = 'anydoinumber';
$this->client = new Client();
$this->Url = 'https://api.crossref.org/works/:'.$this->doi;
$res = $this->client->get($this->Url);
$decoded_items = json_decode($res->getBody(), true);
if (isset($decoded_items['message']['issn-type'])) {
$this->issn = '';
} else {
// no electronic ISSN given
Log.Alert('No electronic ISSN for :'.$this->Doi);
}
The output I'm expecting
$this->issn = "2339-1623"
You can use laravel collection:
collect($array)->where('type', 'electronic')->first();
And output is:
array:2 [
"value" => "2339-1623"
"type" => "electronic"
]
You could use a simple foreach loop that adds matching elements to a results array
$filtered = [];
foreach($myarr as $i){
if($i['type'] == 'searched type')
$filtered[] = $i;
}
or you can break out of the loop when you encounter first element of given type
foreach($myarr as $i){
if($i['type'] == 'searched type')
return $i; // or $found = $i and then break;
}
PHP way:
$searchingFor = 'electronic';
$filteredArray = array_filter($initialArray, function($v, $k) use ($searchingFor) {
return $searchingFor === $v['type'];
}, ARRAY_FILTER_USE_BOTH);
//var_dump($filteredArray);
Docs.
You Have To user foreach loop
$searchterm = 'electronics';
foreach($nested as $key => $value) {
if($value['type'] == $searchterm) {
return $value['value'];
break;
}
}
This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed last month.
I have an array which is multidimensional for no reason
/* This is how my array is currently */
Array
(
[0] => Array
(
[0] => Array
(
[plan] => basic
)
[1] => Array
(
[plan] => small
)
[2] => Array
(
[plan] => novice
)
[3] => Array
(
[plan] => professional
)
[4] => Array
(
[plan] => master
)
[5] => Array
(
[plan] => promo
)
[6] => Array
(
[plan] => newplan
)
)
)
I want to convert this array into this form
/*Now, I want to simply it down to this*/
Array (
[0] => basic
[1] => small
[2] => novice
[3] => professional
[4] => master
[5] => promo
[6] => newplan
)
Any idea how to do this?
This single line would do that:
$array = array_column($array, 'plan');
The first argument is an array | The second argument is an array key.
For details, go to official documentation: https://www.php.net/manual/en/function.array-column.php.
Assuming this array may or may not be redundantly nested and you're unsure of how deep it goes, this should flatten it for you:
function array_flatten($array) {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, array_flatten($value));
}
else {
$result[$key] = $value;
}
}
return $result;
}
If you come across a multidimensional array that is pure data, like this one below, then you can use a single call to array_merge() to do the job via reflection:
$arrayMult = [ ['a','b'] , ['c', 'd'] ];
$arraySingle = call_user_func_array('array_merge', $arrayMult);
// $arraySingle is now = ['a','b', 'c', 'd'];
Just assign it to it's own first element:
$array = $array[0];
For this particular case, this'll do:
$array = array_map('current', $array[0]);
It's basically the exact same question is this one, look at some answers there: PHP array merge from unknown number of parameters.
$singleArray = array();
foreach ($multiDimensionalArray as $key => $value){
$singleArray[$key] = $value['plan'];
}
this is best way to create a array from multiDimensionalArray array.
thanks
Problem array:
array:2 [▼
0 => array:3 [▼
0 => array:4 [▼
"id" => 8
"name" => "Veggie Burger"
"image" => ""
"Category_type" => "product"
]
1 => array:4 [▼
"id" => 9
"name" => "Veggie Pitta"
"image" => ""
"Category_type" => "product"
]
2 => array:4 [▼
"id" => 10
"name" => "Veggie Wrap"
"image" => ""
"Category_type" => "product"
]
]
1 => array:2 [▼
0 => array:4 [▼
"id" => 18
"name" => "Cans 330ml"
"image" => ""
"Category_type" => "product"
]
1 => array:4 [▼
"id" => 19
"name" => "Bottles 1.5 Ltr"
"image" => ""
"Category_type" => "product"
]
]
]
Solution array:
array:5 [▼
0 => array:4 [▼
"id" => 8
"name" => "Veggie Burger"
"image" => ""
"Category_type" => "product"
]
1 => array:4 [▼
"id" => 9
"name" => "Veggie Pitta"
"image" => ""
"Category_type" => "product"
]
2 => array:4 [▼
"id" => 10
"name" => "Veggie Wrap"
"image" => ""
"Category_type" => "product"
]
3 => array:4 [▼
"id" => 18
"name" => "Cans 330ml"
"image" => ""
"Category_type" => "product"
]
4 => array:4 [▼
"id" => 19
"name" => "Bottles 1.5 Ltr"
"image" => ""
"Category_type" => "product"
]
]
Write this code and get your solution , $subcate is your multi dimensional array.
$singleArrayForCategory = array_reduce($subcate, 'array_merge', array());
none of answers helped me, in case when I had several levels of nested arrays. the solution is almost same as #AlienWebguy already did, but with tiny difference.
function nestedToSingle(array $array)
{
$singleDimArray = [];
foreach ($array as $item) {
if (is_array($item)) {
$singleDimArray = array_merge($singleDimArray, nestedToSingle($item));
} else {
$singleDimArray[] = $item;
}
}
return $singleDimArray;
}
test example
$array = [
'first',
'second',
[
'third',
'fourth',
],
'fifth',
[
'sixth',
[
'seventh',
'eighth',
[
'ninth',
[
[
'tenth'
]
]
],
'eleventh'
]
],
'twelfth'
];
$array = nestedToSingle($array);
print_r($array);
//output
array:12 [
0 => "first"
1 => "second"
2 => "third"
3 => "fourth"
4 => "fifth"
5 => "sixth"
6 => "seventh"
7 => "eighth"
8 => "ninth"
9 => "tenth"
10 => "eleventh"
11 => "twelfth"
]
You can do it just using a loop.
$singleArray = array();
foreach ($multiDimensionalArray as $key => $value){
$singleArray[$key] = $value['plan'];
}
Your sample array has 3 levels. Because the first level has only [0], you can hardcode your access into it and avoid an extra function/construct call.
(Code Demos)
array_walk_recursive() is handy and versatile, but for this task may be overkill and certainly a bit more convoluted in terms of readability.
array_walk_recursive($array, function($leafvalue)use(&$flat){$flat[] = $leafvalue;});
var_export($flat);
If this was my code, I'd be using array_column() because it is direct and speaks literally about the action being performed.
var_export(array_column($array[0], 'plan'));
Of course a couple of `foreach() loops will perform very efficiently because language constructs generally perform more efficiently than function calls.
foreach ($array[0] as $plans) {
foreach ($plans as $value) {
$flat[] = $value;
}
}
var_export($flat);
Finally, as a funky alternative (which I can't imagine actually putting to use unless I was writing code for someone whom I didn't care for) I'll offer an array_merge_recursive() call with a splat operator (...).
var_export(array_merge_recursive(...$array[0])['plan']);
Despite that array_column will work nice here, in case you need to flatten any array no matter of it's internal structure you can use this array library to achieve it without ease:
$flattened = Arr::flatten($array);
which will produce exactly the array you want.
This simple code you can use
$array = array_column($array, 'value', 'key');
Recently I've been using AlienWebguy's array_flatten function but it gave me a problem that was very hard to find the cause of.
array_merge causes problems, and this isn't the first time that I've made problems with it either. If you have the same array keys in one inner array that you do in another, then the later values will overwrite the previous ones in the merged array.
Here's a different version of array_flatten without using array_merge:
function array_flatten($array) {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$arrayList=array_flatten($value);
foreach ($arrayList as $listItem) {
$result[] = $listItem;
}
}
else {
$result[$key] = $value;
}
}
return $result;
}
There is an error in most voted answer. Here is the correct version.
function array_flatten($array) {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, array_flatten($value));
}
else {
$result[] = $value;
}
}
return $result;
}
The difference is on the line $result[] = $value;
Original answer was $result[$key] = $value;
The $key index is incorrect after flattering any array in the cycle.
Following this pattern
$input = array(10, 20, array(30, 40), array('key1' => '50', 'key2'=>array(60), 70));
Call the function :
echo "<pre>";print_r(flatten_array($input, $output=null));
Function Declaration :
function flatten_array($input, $output=null) {
if($input == null) return null;
if($output == null) $output = array();
foreach($input as $value) {
if(is_array($value)) {
$output = flatten_array($value, $output);
} else {
array_push($output, $value);
}
}
return $output;
}
I've written a complement to the accepted answer. In case someone, like myself need a prefixed version of the keys, this can be helpful.
Array
(
[root] => Array
(
[url] => http://localhost/misc/markia
)
)
Array
(
[root.url] => http://localhost/misc/markia
)
<?php
function flattenOptions($array, $old = '') {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, flattenOptions($value, $key));
}
else {
$result[$old . '.' . $key] = $value;
}
}
return $result;
}
I had come across the same requirement to flatter multidimensional array into single dimensional array than search value using text in key. here is my code
$data = '{
"json_data": [{
"downtime": true,
"pfix": {
"max": 100,
"threshold": 880
},
"ints": {
"int": [{
"rle": "pri",
"device": "laptop",
"int": "Ether3",
"ip": "127.0.0.3"
}],
"eth": {
"lan": 57
}
}
},
{
"downtime": false,
"lsi": "987654",
"pfix": {
"min": 10000,
"threshold": 890
},
"mana": {
"mode": "NONE"
},
"ints": {
"int": [{
"rle": "sre",
"device": "desk",
"int": "Ten",
"ip": "1.1.1.1",
"UF": true
}],
"ethernet": {
"lan": 2
}
}
}
]
}
';
$data = json_decode($data,true);
$stack = &$data;
$separator = '.';
$toc = array();
while ($stack) {
list($key, $value) = each($stack);
unset($stack[$key]);
if (is_array($value)) {
$build = array($key => ''); # numbering without a title.
foreach ($value as $subKey => $node)
$build[$key . $separator . $subKey] = $node;
$stack = $build + $stack;
continue;
}
if(!is_numeric($key)){
$toc[$key] = $value;
}
}
echo '<pre/>';
print_r($toc);
My output:
Array
(
[json_data] =>
[json_data.0] =>
[json_data.0.downtime] => 1
[json_data.0.pfix] =>
[json_data.0.pfix.max] => 100
[json_data.0.pfix.threshold] => 880
[json_data.0.ints] =>
[json_data.0.ints.int] =>
[json_data.0.ints.int.0] =>
[json_data.0.ints.int.0.rle] => pri
[json_data.0.ints.int.0.device] => laptop
[json_data.0.ints.int.0.int] => Ether3
[json_data.0.ints.int.0.ip] => 127.0.0.3
[json_data.0.ints.eth] =>
[json_data.0.ints.eth.lan] => 57
[json_data.1] =>
[json_data.1.downtime] =>
[json_data.1.lsi] => 987654
[json_data.1.pfix] =>
[json_data.1.pfix.min] => 10000
[json_data.1.pfix.threshold] => 890
[json_data.1.mana] =>
[json_data.1.mana.mode] => NONE
[json_data.1.ints] =>
[json_data.1.ints.int] =>
[json_data.1.ints.int.0] =>
[json_data.1.ints.int.0.rle] => sre
[json_data.1.ints.int.0.device] => desk
[json_data.1.ints.int.0.int] => Ten
[json_data.1.ints.int.0.ip] => 1.1.1.1
[json_data.1.ints.int.0.UF] => 1
[json_data.1.ints.ethernet] =>
[json_data.1.ints.ethernet.lan] => 2
)
This is my contribuition
function arrayUnica($array, $prefix = "")
{
if (!is_array($array)) {
return false;
}
$new_array = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
$key = is_int($key) ? $prefix . $key . "-" : $key . "_";
$new_array = array_merge($new_array, arrayUnica($value, $key));
} else {
$new_array[$prefix . $key] = $value;
}
}
return $new_array;
}
Hope this will helpful for you,
$array= 'YOUR_MULTIDIMENSIONAL_ARRAY';
$arr=[];
array_walk_recursive($array, function($k){global $arr; $arr[]=$k;});
print_r($arr);
I have done this with OOP style
$res=[1=>[2,3,7,8,19],3=>[4,12],2=>[5,9],5=>6,7=>[10,13],10=>[11,18],8=>[14,20],12=>15,6=>[16,17]];
class MultiToSingle{
public $result=[];
public function __construct($array){
if(!is_array($array)){
echo "Give a array";
}
foreach($array as $key => $value){
if(is_array($value)){
for($i=0;$i<count($value);$i++){
$this->result[]=$value[$i];
}
}else{
$this->result[]=$value;
}
}
}
}
$obj= new MultiToSingle($res);
$array=$obj->result;
print_r($array);
Multi dimensional array to single array with one line code !!!
Enjoy the code.
$array=[1=>[2,5=>[4,2],[7,8=>[3,6]],5],4];
$arr=[];
array_walk_recursive($array, function($k){global $arr; $arr[]=$k;});
print_r($arr);
...Enjoy the code.
Try this it works for me:
$newArray = array();
foreach($operator_call_logs as $array) {
foreach($array as $k=>$v) {
$newArray[$k] = $v;
}
}
Save this as a php file, simply import and use single_array() function
<?php
$GLOBALS['single_array']=[];
function array_conveter($array_list){
if(is_array($array_list)){
foreach($array_list as $array_ele){
if(is_array($array_ele)){
array_conveter($array_ele);
}else{
array_push($GLOBALS['single_array'],$array_ele);
}
}
}else{
array_push($GLOBALS['single_array'],$array_list);
}
}
function single_array($mix){
foreach($mix as $single){
array_conveter($single);
}return $GLOBALS['single_array'];
$GLOBALS['single_array']=[];
}
/* Example convert your multi array to single */
$mix_array=[3,4,5,[4,6,6,7],'abc'];
print_r(single_array($mix_array));
?>
if use php version 7.4 and above
$users = [
[
'Ahmed',
'Mohammed',
],
[
'Saeed',
'Rami',
'Haider',
],
];
$admin = array_merge(...$users);