php recursive key renaming for inner arrays only - php

i am in need of bit direction here for renaming my inner child keys who inner depth is unknown. Original array is parent child multidimensional array created via id and parent_id relation. Here's a one example of array
$testArray = array (
"name" => "Test name",
"someValue1" => 834.69,
"someMoreValue" => 33.4,
"someCode" => 6668,
"child" => array
(
array
(
"name" => "Some name",
"someValue1" => 471.05,
"someMoreValue" => 18.84,
"someCode" => 7064,
"child" => array
(
array
(
"name" => "Yet another name",
"someValue1" => 438.62,
"someMoreValue" => 17.56,
"someCode" => 7065
),
array
(
"name" => "Da name",
"someValue1" => 4444,
"someMoreValue" => 44,
"someCode" => 7044
)
)
),
array
(
"name" => "name",
"someValue1" => 2222,
"someMoreValue" => 22,
"someCode" => 7022
)
)
);
here's my trying so far, i am able to rename the first level of childs only.
function keyprefix($keyprefix, $keyprefix2, Array $array) {
foreach($array as $k=>$v){
$array[$keyprefix.'-'.$k.'-'.$keyprefix2] = $v;
unset($array[$k]);
}
return $array;
}
function test($array) {
$newArr = array();
foreach ($array as $key => $value) {
// $newArr[] = is_array($value) ? test($value) : $value;
// $newArr[] = is_array($value) ? $array : array_merge( keyprefix("$name","Alt Danışman", $array[$key]) );
$index = 0;
$name = $array['name'];
if (is_array($value)) {
//if (is_array($value)) {
// test($value);
//}
$newArr[$key] = array_merge(
keyprefix("$name","Under Child", $array[$key])
);
}
else {
$newArr[$key] = $value;
}
}
return $newArr;
}
echo highlight_string(var_export(test($testArray), true));
Any ideas on how I can approach this? I feel that I am close just need a little guide in the right path. I have seen many examples of stack-overflow etc but need some help. I know recursion is not my best skill yet.

function TryRenameChildren(array $array)
{
if(isset($array['child']))
{
$array['child'] = keyprefix($array['name'], 'prefix2', $array['child']);
foreach($array['child'] as $key => $value)
if(is_array($value))
$array['child'][$key] = TryRenameChildren($value);
}
return $array;
}
$testArray = TryRenameChildren($testArray);

Related

json merge in multidimensional array decode not working [duplicate]

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

Search in a multidimensional assoc array

I have an array, looking like this:
[lund] => Array
(
[69] => foo
)
[berlin] => Array
(
[138] => foox2
)
[tokyo] => Array
(
[180] => foox2
[109] => Big entrance
[73] => foo
)
The thing is that there were duplicate keys, so I re-arranged them so I can search more specifically, I thought.
Previously I could just
$key = array_search('foo', $array);
to get the key but now I don't know how.
Question: I need key for value foo, from tokyo. How do I do that?
You can get all keys and value of foo by using this:
foreach ($array as $key => $value) {
$newArr[$key] = array_search('foo', $value);
}
print_r(array_filter($newArr));
Result is:
Array
(
[lund] => 69
[tokyo] => 109
)
If you don't mind about the hard code than you can use this:
array_search('foo', $array['tokyo']);
It just a simple example, you can modify it as per your requirement.
Try this
$a = array(
"land"=> array("69"=>"foo"),
"land1"=> array("138"=>"foo1"),
"land2"=> array('180' => 'foox2',
'109' => 'Big entrance',
'73' => 'foo'),
);
//print_r($a);
$reply = search_in_array($a, "foo");
print_r($reply);
function search_in_array($a, $search)
{
$result = array();
foreach($a as $key1 => $array ) {
foreach($array as $k => $value) {
if($value == "$search") {
array_push($result,"{$key1}=>{$k}");
breck;
}
}
}
return $result;
}
This function will return the key or null if the search value is not found.
function search($searchKey, $searchValue, $searchArr)
{
foreach ($searchArr as $key => $value) {
if ($key == $searchKey && in_array($searchValue, $value)) {
$results = array_search($searchValue, $value);
}
}
return isset($results) ? $results : null;
}
// var_dump(search('tokyo', 'foo', $array));
Since Question: I need key for value foo, from tokyo. How do i do that?
$key = array_search('foo', $array['tokyo']);
As a function:
function getKey($keyword, $city, $array) {
return array_search($keyword, $array[$city]);
}
// PS. Might be a good idea to wrap this array in an object and make getKey an object method.
If you want to get all cities (for example to loop through them):
$cities = array_keys($array);
I created solution using array iterator. Have a look on below solution:
$array = array(
'lund' => array
(
'69' => 'foo'
),
'berlin' => array
(
'138' => 'foox2'
),
'tokyo' => array
(
'180' => 'foox2',
'109' => 'Big entrance',
'73' => 'foo'
)
);
$main_key = 'tokyo'; //key of array
$search_value = 'foo'; //value which need to be search
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach ($iterator as $key => $value) {
$keys = array();
if ($value == $search_value) {
$keys[] = $key;
for ($i = $iterator->getDepth() - 1; $i >= 0; $i--) {
$keys[] = $iterator->getSubIterator($i)->key();
}
$key_paths = array_reverse($keys);
if(in_array($main_key, $key_paths) !== false) {
echo "'{$key}' have '{$value}' value which traverse path is: " . implode(' -> ', $key_paths) . '<br>';
}
}
}
you can change value of $main_key and $serch_value according to your parameter. hope this will help you.
<?php
$lund = [
'69' => 'foo'
];
$berlin = [
'138' => 'foox2'
];
$tokyo = [
'180' => 'foox2',
'109' => 'Big entrance',
'73' => 'foo'
];
$array = [
$lund,
$berlin,
$tokyo
];
echo $array[2]['180']; // outputs 'foox2' from $tokyo array
?>
If you want to get key by specific key and value then your code should be:
function search_array($array, $key, $value)
{
if(is_array($array[$key])) {
return array_search($value, $array[$key]);
}
}
echo search_array($arr, 'tokyo', 'foo');
try this:
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 'On');
$array=array("lund" => array
(
69 => "foo"
),
"berlin" => array
(
138 => "foox2"
),
"tokyo" => array
(
180 => "foox2",
109 => "Big entrance",
73 => "foo"
));
function search($array, $arrkey1, $arrvalue2){
foreach($array as $arrkey=>$arrvalue){
if($arrkey == $arrkey1){
foreach($arrvalue as $arrkey=>$arrvalue){
if(preg_match("/$arrvalue/i",$arrvalue2))
return $arrkey;
}
}
}
}
$result=search($array, "tokyo", "foo"); //$array=array; tokyo="inside array to check"; foo="value" to check
echo $result;
You need to loop through array, since its 2 dimensional in this case. And then find corresponding value.
foreach($arr as $key1 => $key2 ) {
foreach($key2 as $k => $value) {
if($value == "foo") {
echo "{$k} => {$value}";
}
}
}
This example match key with $value, but you can do match with $k also, which in this case is $key2.

Find values in multidimensional arrays

I've a multidimensional array:
array (
array (
"username" => "foo",
"favoriteGame" => "Mario"
)
array (
"username" => "bar",
"favoriteGame" => "Mario"
)
array (
"username" => "xyz",
"favoriteGame" => "Zelda"
)
)
How could I get the usernames of the persons that like to play for example Mario the easiest way possible?
EDIT:
My fault: forget to explicitly mention that the "favoriteGame" value is dynamic and I cannot know which it is in advance.
My Solution:
foreach($users as $key => $value)
{
if(!isset($$value['favoriteGame']))
{
$$value['favoriteGame'] = array();
}
array_push($$value['favoriteGame'], $value['username']);
}
Iterate over each sub-array and find its favoriteGame value.
If there is not already an array $favoriteGame create it.
Push the username-value of the actual sub-array to the $favoriteGame array.
Thanks for your replies, I just couldn't phrase this question properly.
function getUsernamesByFavoriteGame($data, $game) {
$usernames = array();
foreach($data as $arr) {
if ($arr['favoriteGame'] == $game) {
$usernames[] = $arr['username'];
}
}
return $usernames;
}
$usernames = array();
foreach($array as $key => $value) {
if ($value['favoriteGame'] == 'Mario') {
$usernames[] = $value['username'];
}
}
I would use array_filter. If you have PHP 5.3 or up, you can do it like this:
$favorite = "Mario";
$filter = function($player) use($favorite) { return $player['favoriteGame'] == $favorite; };
$filtered = array_filter($players, $filter);
It will be a little different for older versions because you won't be able to use lambda functions.
$game = 'Mario';
$users = array();
foreach($array as $key => $value) {
if ($value['favoriteGame'] == $game) {
$users[] = $value['username'];
}
}
If you are using this more often then convert the data structure to something like this.
array(
"Mario" => array(
"0":"foo",
"1":"xyz"
)
"Zelda" => array(
"0":"pqr",
"1":"abc"
)
)
This will directly give you list of user names for a favorite game.
$arr[$favGame]
If you cannot change the data structure then go with with tigrang has suggested.
I think you should implement a custom multidimensional search function.
Take a look at this answer.
Here's how you would use it
Code | Live example
function search($array, $key, $value){
$results = array();
if (is_array($array))
{
if (isset($array[$key]) && $array[$key] == $value)
$results[] = $array;
foreach ($array as $subarray)
$results = array_merge($results, search($subarray, $key, $value));
}
return $results;
}
$arr = array (
array (
"username" => "foo",
"favoriteGame" => "Mario"
),
array (
"username" => "bar",
"favoriteGame" => "Mario"
),
array (
"username" => "xyz",
"favoriteGame" => "Zelda"
)
);
print_r(search($arr, 'favoriteGame', 'Mario'));
//OUTPUT
Array (
[0] => Array (
[username] => foo
[favoriteGame] => Mario
)
[1] => Array (
[username] => bar
[favoriteGame] => Mario
)
)
$array = array( 'a' => 'A',
'b'=>'B',
'c'=>'C',
'd'=>array(
'e'=>array(
'f'=>'D'
),
'g'=>array(
'h'=>'E'
)
),
'i'=>'F',
'j'=>array(
'k'=>'G'
),
'l'=>'H'
);
$new_array = array();
foreach($array as $k1=>$v1){
if(is_array($v1)){
$new_array = parseArray($new_array, $k1, $v1);
}else{
$new_array = array_merge($new_array, array($k1=>$v1));
}
}
function parseArray($new_array, $key, $val){
if(is_array($val)){
foreach($val as $k2=>$v2){
if(is_array($v2)){
$new_array = parseArray($new_array, $k2, $v2);
}else{
$new_array = array_merge($new_array, array($k2=>$v2));
}
}
}else{
$new_array = array_merge($new_array, array($key=>$val));
}
return $new_array;
}
Output
Array
(
[a] => A
[b] => B
[c] => C
[f] => D
[h] => E
[i] => F
[k] => G
[l] => H
)

Convert multidimensional array into single array [duplicate]

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

Taking a string of period separated properties and converting it to a json object in php

I'm fairly sure I'm missing something blindingly obvious here but here it goes.
I am working on updating a search function in an application which was running a loop and doing a very large number of sql queries to get object / table relations to one large query that returns everything. However the only way I could think to return relations was period separated, what I am now wanting to do is take the flat array of keys and values and convert it into an associative array to then be jsonified with json_encode.
For example what I have is this...
array(
"ID"=>10,
"CompanyName"=>"Some Company",
"CompanyStatusID"=>2,
"CompanyStatus.Status"=>"Active",
"addressID"=>134,
"address.postcode"=>"XXX XXXX",
"address.street"=>"Some Street"
);
And what I want to turn it into is this...
array(
"ID"=>10,
"CompanyName"=>"Some Company",
"CompanyStatusID"=>2,
"CompanyStatus"=>array(
"Status"=>"Active"
),
"addressID"=>134,
"address"=>array(
"postcode"=>"XXX XXXX",
"street"=>"Some Street"
)
);
Now I'm sure this should be a fairly simple recursive loop but for the life of me this morning I can't figure it out.
Any help is greatly appreciated.
Regards
Graham.
Your function was part way there mike, though it had the problem that the top level value kept getting reset on each pass of the array so only the last period separated property made it in.
Please see updated version.
function parse_array($src) {
$dst = array();
foreach($src as $key => $val) {
$parts = explode(".", $key);
if(count($parts) > 1) {
$index = &$dst;
$i = 0;
$count = count($parts)-1;
foreach(array_slice($parts,0) as $part) {
if($i == $count) {
$index[$part] = $val;
} else {
if(!isset($index[$part])){
$index[$part] = array();
}
}
$index = &$index[$part];
$i++;
}
} else {
$dst[$parts[0]] = $val;
}
}
return $dst;
}
I am sure there is something more elegant, but quick and dirty:
$arr = array(
"ID"=>10,
"CompanyName"=>"Some Company",
"CompanyStatusID"=>2,
"CompanyStatus.Status"=>"Active",
"addressID"=>134,
"address.postcode"=>"XXX XXXX",
"address.street"=>"Some Street"
);
$narr = array();
foreach($arr as $key=>$val)
{
if (preg_match("~\.~", $key))
{
$parts = split("\.", $key);
$narr [$parts[0]][$parts[1]] = $val;
}
else $narr [$key] = $val;
}
$arr = array(
"ID" => 10,
"CompanyName" => "Some Company",
"CompanyStatusID" => 2,
"CompanyStatus.Status" => "Active",
"addressID" => 134,
"address.postcode" => "XXX XXXX",
"address.street" => "Some Street",
"1.2.3.4.5" => "Some nested value"
);
function parse_array ($src) {
$dst = array();
foreach($src as $key => $val) {
$parts = explode(".", $key);
$dst[$parts[0]] = $val;
if(count($parts) > 1) {
$index = &$dst[$parts[0]];
foreach(array_slice($parts, 1) as $part) {
$index = array($part => $val);
$index = &$index[$part];
}
}
}
return $dst;
}
print_r(parse_array($arr));
Outputs:
Array
(
[ID] => 10
[CompanyName] => Some Company
[CompanyStatusID] => 2
[CompanyStatus] => Array
(
[Status] => Active
)
[addressID] => 134
[address] => Array
(
[street] => Some Street
)
[1] => Array
(
[2] => Array
(
[3] => Array
(
[4] => Array
(
[5] => Some nested value
)
)
)
)
)

Categories