PHP - dynamically add dimensions to array - php

I have a :
$value = "val";
I also have an array :
$keys = ['key1', 'key2', 'key3'...]
The keys in that array are dynamically generated, and can go from 2 to 10 or more entries.
My goal is getting this :
$array['key1']['key2']['key3']... = $value;
How can I do that ?
Thanks

The easiest, and least messy way (ie not using references) would be to use a recursive function:
function addArrayLevels(array $keys, array $target)
{
if ($keys) {
$key = array_shift($keys);
$target[$key] = addArrayLevels($keys, []);
}
return $target;
}
//usage
$keys = range(1, 10);
$subArrays = addARrayLevels($keys, []);
It works as you can see here.
How it works is really quite simple:
if ($keys) {: if there's a key left to be added
$key = array_shift($keys); shift the first element from the array
$target[$key] = addArrayLevels($keys, []);: add the index to $target, and call the same function again with $keys (after having removed the first value). These recursive calls will go on until $keys is empty, and the function simply returns an empty array
The downsides:
Recursion can be tricky to get your head round at first, especially in complex functions, in code you didn't write, but document it well and you should be fine
The pro's:
It's more flexible (you can use $target as a sort of default/final assignment variable, with little effort (will add example below if I find the time)
No reference mess and risks to deal with
Example using adaptation of the function above to assign value at "lowest" level:
function addArrayLevels(array $keys, $value)
{
$return = [];
$key = array_shift($keys);
if ($keys) {
$return[$key] = addArrayLevels($keys, $value);
} else {
$return[$key] = $value;
}
return $return;
}
$keys = range(1, 10);
$subArrays = addARrayLevels($keys, 'innerValue');
var_dump($subArrays);
Demo

I don't think that there is built-in function for that but you can do that with simple foreach and references.
$newArray = [];
$keys = ['key1', 'key2', 'key3'];
$reference =& $newArray;
foreach ($keys as $key) {
$reference[$key] = [];
$reference =& $reference[$key];
}
unset($reference);
var_dump($newArray);

Related

Reform PHP associated array

I have an associative array:
$input = [
['key'=>'x', 'value'=>'a'],
['key'=>'x', 'value'=>'b'],
['key'=>'x', 'value'=>'c'],
['key'=>'y', 'value'=>'d'],
['key'=>'y', 'value'=>'e'],
['key'=>'z', 'value'=>'f'],
['key'=>'m', 'value'=>'n'],
];
And I want to reform it simple in:
$output = [
'x'=>['a','b','c'],
'y'=>['d','e'],
'z'=>'f',
'm'=>'n'
]
So basically, conditions are:
1. If same key found then put values in an array.
2. If no same key found then value remains string.
You can replace associative array with object if you are more comfortable with objects.
Here is my working solution for this problem:
foreach($input as $in){
if(!empty($output[$in['key']])){
if(is_array($output[$in['key']])){
$output[$in['key']][] = $in['value'];
continue;
}
$output[$in['key']] = [$output[$in['key']],$in['value']];
continue;
}
$output[$in['key']] = $in['value'];
}
print_r($output);
However I believe that it can be done in much compact and efficient way.
Please comment your answers if someone has better solution.
Your help is much appreciated!
Reformat array to [ [ x=>a ], [x=>b],.. ] and merge all sub-arrays
$input = array_map(function($x) { return [$x['key'] => $x['value']]; }, $input);
$input = array_merge_recursive(...$input);
print_r($input);
demo
I would suggest
<?php
$input = [
['key'=>'x', 'value'=>'a'],
['key'=>'x', 'value'=>'b'],
['key'=>'x', 'value'=>'c'],
['key'=>'y', 'value'=>'d'],
['key'=>'y', 'value'=>'e'],
['key'=>'z', 'value'=>'f'],
['key'=>'m', 'value'=>'n'],
];
$reducer = function($carry, $item) {
$carry[$item['key']][] = $item['value'];
return $carry;
};
$mapper = function ($item) {
if (count($item) === 1) {
return $item[0];
}
return $item;
};
$output = array_map($mapper, array_reduce($input, $reducer, []));
var_dump($output);
You can see the result here: https://3v4l.org/8JjjS
You can use array_reduce to loop over an existing array and build up a new one:
$output = array_reduce($input, function ($carry, $i) {
$carry[$i['key']][] = $i['value'];
return $carry;
}, []);
Each element in $input is passed to the anonymous function, along with the $carry variable that's being built up as we go along. Inside, we just add each value to a sub-element indexed by key. The third argument [] is to set the initial value of the result to an empty array.
See https://eval.in/935015
(I'm assuming that the duplicate x keys in the question are a typo, and that the second is supposed to z, since that matches up with your suggested output)
For your original code you may find extract() interesting. I replaced the continue-s with else-s, but that is more like a matter of taste:
foreach($input as $in){
extract($in);
if(!empty($output[$key])){
if(is_array($output[$key])){
$output[$key][] = $value;
} else {
$output[$key] = [$output[$key],$value];
}
} else {
$output[$key] = $value;
}
On a side note I would probably use two much simpler loops, one for building lists and another for extracting single elements:
foreach($input as $in){
$output[$in['key']][] = $in['value'];
/* or: extract($in);
$output[$key][]=$value; */
}
foreach($output as $key => $value){
if(count($value)==1){
$output[$key]=$value[0];
}
}

remove value from array what the words is not fully match

How i can remove a value from array what is not fully match the letters.
Array code example:
$Array = array(
'Funny',
'funnY',
'Games',
);
How I can unset all values from this array what is 'funny'
I try via unset('funny'); but is not removing the values from array, is removed just if i have 'funny' on array but 'funnY' or 'Funny' not working
Maybe there is some sophisticated solution with array_intersect_key or something which could do this in one line but I assume this approach is more easily read:
function removeCaseInsensitive($array, $toRemove) {
$ret = [];
foreach ($array as $v) {
if (strtolower($v) != strtolower($toRemove))
$ret[] = $v;
}
return $ret;
}
This returns a new array that does not contain any case of $toRemove. If you want to keep the keys than you can do this:
function removeCaseInsensitive($array, $toRemove) {
$keep = [];
foreach ($array as $k => $v) {
if (strtolower($v) != strtolower($toRemove))
$keep[$k] = true;
}
return array_intersect_keys($array, $keep);
}
You can filter out those values with a loose filtering rule:
$array = array_filter($array, function($value) {
return strtolower($value) !== 'funny';
});

PHP array_walk_recursive: two approaches, different result

Given the following setup:
$storer = array();
$arr = array(1, 2, 3);
I'm curious why this does not write to $storer...
array_walk_recursive($arr, function($val, $key) {
global $storer;
$storer[] = 'foo';
});
print_r($storer); //no change - empty
..but this does:
array_walk_recursive($arr, function($val, $key) use (&$storer) {
$storer[] = 'foo';
});
print_r($storer); //three items, all 'foo'
Can anyone enlighten me? In a user function I would expect global to provide read/write access.
After pulling my hair out trying to get a flattened array with keys this works:
$result = array();
array_walk_recursive($inputarray,function($v, $k) use (&$result){ $result[$k] = $v; });
$inputarray = $result;
I hope someone finds this and it helps.

php get array element and remove it from array at once

I have array:
$arr = array(
'a' => 1,
'b' => 2,
'c' => 3
);
Is there built-in php function which gets array value by key and then removes element from this array?
I know array_shift and array_pop functions, but I need to get element by custom key, not first/last element. Something like:
$arr; // 'a'=>1, 'b'=>2, 'c'=>3
$elem = array_shift_key($arr, 'b');
echo $elem; // 2
$arr; // 'a'=>1, 'c'=>3
Not sure about native way, but this should work:
function shiftByKey($key, &$array) {
if (!array_key_exists($key, $array)) {
return false;
}
$tmp = $array[$key];
unset($array[$key]);
return $tmp;
}
Edit: Updated it so that array is passed by reference. Else your array stays the same.
As far as I'm aware there's nothing that comes close to that. Can be written easily though:
function array_shift_key(array &$array, $key) {
$value = $array[$key];
unset($array[$key]);
return $value;
}
If you care, validate first whether the key exists in the array and do something according to your error handling philosophy if it doesn't. Otherwise you'll simply get a standard PHP notice for non-existing keys.
function array_shift_key(array &$input, $key) {
$value = null;
// Probably key presents with null value
if (isset($input[$key]) || array_key_exists($key, $input)) {
$value = $input[$key];
unset($input[$key]);
}
return $value;
}

Convert delimited string into array key path and assign value

I have a string like this:
$string = 'one/two/three/four';
which I turn it into a array:
$keys = explode('/', $string);
This array can have any number of elements, like 1, 2, 5 etc.
How can I assign a certain value to a multidimensional array, but use the $keys I created above to identify the position where to insert?
Like:
$arr['one']['two']['three']['four'] = 'value';
Sorry if the question is confusing, but I don't know how to explain it better
This is kind of non-trivial because you want to nest, but it should go something like:
function insert_using_keys($arr, $keys, $value){
// we're modifying a copy of $arr, but here
// we obtain a reference to it. we move the
// reference in order to set the values.
$a = &$arr;
while( count($keys) > 0 ){
// get next first key
$k = array_shift($keys);
// if $a isn't an array already, make it one
if(!is_array($a)){
$a = array();
}
// move the reference deeper
$a = &$a[$k];
}
$a = $value;
// return a copy of $arr with the value set
return $arr;
}
$string = 'one/two/three/four';
$keys = explode('/', $string);
$arr = array(); // some big array with lots of dimensions
$ref = &$arr;
while ($key = array_shift($keys)) {
$ref = &$ref[$key];
}
$ref = 'value';
What this is doing:
Using a variable, $ref, to keep track of a reference to the current dimension of $arr.
Looping through $keys one at a time, referencing the $key element of the current reference.
Setting the value to the final reference.
You'll need to first make sure the key's exist, then assign the value. Something like this should work (untested):
function addValueByNestedKey(&$array, $keys, $value) {
$branch = &$array;
$key = array_shift($keys);
// add keys, maintaining reference to latest branch:
while(count($keys)) {
$key = array_pop($keys);
if(!array_key_exists($key, $branch) {
$branch[$key] = array();
}
$branch = &$branch[$key];
}
$branch[$key] = $value;
}
// usage:
$arr = array();
$keys = explode('/', 'one/two/three/four');
addValueByNestedKey($arr, $keys, 'value');
it's corny but:
function setValueByArrayKeys($array_keys, &$multi, $value) {
$m = &$multi
foreach ($array_keys as $k){
$m = &$m[$k];
}
$m = $value;
}
$arr['one']['two']['three']['four'] = 'value';
$string = 'one/two/three/four';
$ExpCheck = explode("/", $string);
$CheckVal = $arr;
foreach($ExpCheck AS $eVal){
$CheckVal = $CheckVal[$eVal]??false;
if (!$CheckVal)
break;
}
if ($CheckVal) {
$val =$CheckVal;
}
this will give u your value in array.

Categories