I've got an array containing values I wish to use as keys, such as:
$keys = array("first", "second", "third", "fourth");
The count and contents of these values will be changing dynamically within a loop. I want them to become the keys of a multidimensional array, but the count of the keys array will always be changing, so while this would work for that first array of keys:
$multidimensional[$keys[0]][$keys[1]][$keys[2]][$keys[3]] = "some value";
Later in the loop the keys may be something like:
$keys = array("first", "second", "gamma", "delta", "theta", "kappa");
So using this in the loop:
$multidimensional[$keys[0]][$keys[1]][$keys[2]][$keys[3]] = "some value";
Will not work, and needs to be dynamic too based on the count of the keys.
I've gone through each of the array functions in the PHP manual and can't seem to find something that fulfills this purpose. Am I totally overlooking something basic here? Maybe some curly brace magic?
There you go...
function setMultidimensionalValue($value, array $keys, array $multidimensional)
{
$node = &$multidimensional;
foreach ($keys as $key)
{
if (!isset($node[$key]))
$node[$key] = null;
$node = &$node[$key];
}
$node = $value;
return $multidimensional;
}
// Example of usage
$multidimensional = array();
var_dump(setMultidimensionalValue('value', array('first', 'second', 'third'), $multidimensional));
Related
I have a multi dimension array that I want to merge all the inside arrays into one singer dimension array, I have tried array_merge with foreach but it doesn't help.
Example Array:
$nums = array (
array(1,2,3),
array(4,5,6),
array(7,8,9)
);
What I did but get an empty array
$newArr = [];
foreach ($nums as $value) {
array_merge($newArr, $value);
}
Expectation
$newArr = array(1,2,3,4,5,6,7,8,9)
You could use the function array_merge() this way :
$newArr = array_merge(...$nums)
It would make your code lighter and avoid the use of a foreach loop.
array_merge returns the results of the merge rather than acting on the passed argument like sort() does. You need to be doing:
$newArr = array_merge($newArr, $value);
I have 2 arrays and want to combine into third array with one array as key and another as value. I tried to use array_combine(), but the function will eliminate all the repeated keys, so I want the result array as a 2d array. The sample array is as below:
$keys = {0,1,2,0,1,2,0,1,2};
$values = {a,b,c,d,e,f,g,h,i};
$result = array(
[0]=>array(0=>a,1=>b,2=>c),
[1]=>array(0=>d,1=>e,2=>f),
[2]=>array(0=>g,1=>h,2=>i)
);
//What i am using right now is:
$result = array_combine($keys,$values);
But it only returns array(0=>g,2=>h,3=>i). Any advice would be appreciated!
You can do it like below:-
<?php
$keys = array(0,1,2,0,1,2,0,1,2);
$values = array('a','b','c','d','e','f','g','h','i');
$values = array_chunk($values,count(array_unique($keys)));
foreach($values as &$value){
$value = array_combine(array_unique($keys),$value);
}
print_r($values);
https://eval.in/859753
Yes the above is working and i give upvote too for this but i dont know why you combine into the foreach loop its not necessary. The results are given in only in second line. Can you describe?
<?php
$keys = array(0,1,2,0,1,2,0,1,2);
$values = array('a','b','c','d','e','f','g','h','i');
$v = array_chunk($values,count(array_unique($keys)));
echo "<pre>";print_r($v);
?>
https://eval.in/859759
As a more flexible/robust solution, push key-value pairs into new rows whenever the key's value is already in the currently targeted row. In other words, there will never be an attempt to write a key into a row that already contains that particular key.
This can be expected to be highly efficient because there are no iterated function calls ...no function calls at all, really.
Code: (Demo)
$result = [];
foreach ($keys as $i => $key) {
$counter[$key] = ($counter[$key] ?? -1) + 1;
$result[$counter[$key]][$key] = $values[$i];
}
var_export($result);
I have String which look like this,
1|2|3|4
and I'm creating a array from that string by,
$arr = explode("|", $data['my_list']);
and then from each element of the array i need to pair with another value by creating associative array. After create, it should look like this,
1=>1
1=>2
1=>3
1=>4
so inside a loop I need to create this associative array. Can anybody please explain how to do this
$tempArr = array();
$arr = explode("|", $data['my_list']);
foreach($arr as $item) {
$tempArray['associative_with_key_' . $item] = 5; // where 5 is a new value
}
I have an array with string value in PHP for example : arr['apple'], arr['banana'], and many more -about 20-30 data (get it from some process). Now I want to get its value and return it to one variable.
For example, I have Original array is like this:
$arr['Apple']
$arr['Banana']
and more..
and result that I want is like this:
$arr[0] = "Apple"
$arr[1] = "Banana"
and more..
Any idea how to do that?
Why not using array_keys()?
$new_array = array_keys($array);
Use array_flip()
$new_arr = array_flip($old_arr);
Demonstration
use foreach loop
foreach($arr as $key => $val){
$new_var[] = $key;
}
use array_keys function:
$keys = array_keys($arr);
It returns an array of all the keys in array.
I'm working with an array of data that I've changed the names of some array keys, but I want the data to stay the same basically... Basically I want to be able to keep the data that's in the array stored in the DB, but I want to update the array key names associated with it.
Previously the array would have looked like this: $var_opts['services'] = array('foo-1', 'foo-2', 'foo-3', 'foo-4');
Now the array keys are no longer prefixed with "foo", but rather with "bar" instead. So how can I update the array variable to get rid of the "foos" and replace with "bars" instead?
Like so: $var_opts['services'] = array('bar-1', 'bar-2', 'bar-3', 'bar-4');
I'm already using if(isset($var_opts['services']['foo-1'])) { unset($var_opts['services']['foo-1']); } to get rid of the foos... I just need to figure out how to replace each foo with a bar.
I thought I would use str_replace on the whole array, but to my dismay it only works on strings (go figure, heh) and not arrays.
The idea:
Get a list of all your array keys
Modify each one of them as you choose
Replace the existing keys with the modified ones
The code:
$keys = array_keys($arr);
$values = array_values($arr);
$new_keys = str_replace('foo', 'bar', $keys);
$arr = array_combine($new_keys, $values);
What this actually does is create a new array which has the same values as your original array, but in which the keys have been changed.
Edit: updated as per Kamil's comment below.
For the values you've provided
$var_opts['services'] = array('foo-1', 'foo-2', 'foo-3', 'foo-4');
var_dump($var_opts['services']);
foreach($var_opts['services'] as &$val) {
$val = str_replace('foo', 'bar', $val);
}
unset($val);
var_dump($var_opts['services']);
or if you want to change the actual keys
$var_opts['services'] = array('foo-1' => 1, 'foo-2' => 2, 'foo-3' => 3, 'foo-4' => 4);
var_dump($var_opts['services']);
foreach($var_opts['services'] as $i => $val) {
unset($var_opts['services'][$i]);
$i = str_replace('foo', 'bar', $i);
$var_opts['services'][$i] = $val;
}
var_dump($var_opts['services']);