Modify value of a deep key in an associative array [duplicate] - php

This question already has answers here:
How to access and manipulate multi-dimensional array by key names / path?
(10 answers)
Closed 6 years ago.
Let's assume we have a simple $array like the following.
$array = array(
'a' => array(
'b' => array(
'c' => 'd'
),
'e' => 'f'
),
'g' => 'h'
);
Given an arbitrary array of $keys = array('a', 'b', 'c') and a value $value = 'i', I would like to change value of $array['a']['b']['c'] to i.
For simplicity, let's assume that elements of $keys are all valid, i.e. for any positive j, $keys[j] exists and is a child of $keys[j - 1].
I came up with a solution by passing a reference to the array and looping over keys but my implementation seems a bit ugly. Is there any straight forward way of doing this?

// current key index (starting at 0)
$i = 0;
// current array (starting with the outermost)
$t = &$array;
// continue until keys are exhausted
while ($i < count($keys) - 1) {
// update array pointer based on current key
$t = &$t[$keys[$i++]];
}
// update value at last key
$t[$keys[$i]] = $value;
http://sandbox.onlinephpfunctions.com/code/0598f00ab719c005a0560c18f91ab00154ba9453

Related

How do I pass array keys to an array in PHP [duplicate]

This question already has answers here:
Create an assoc array with equal keys and values from a regular array
(3 answers)
Closed 6 years ago.
I have this array:
$a = array('b', 'c', 'd');
Is there a simple method to convert the array to the following?
$a = array('b' => 'b', 'c' => 'c', 'd' => 'd');
$final_array = array_combine($a, $a);
Reference: http://php.net/array-combine
P.S. Be careful with source array containing duplicated keys like the following:
$a = ['one','two','one'];
Note the duplicated one element.
Be careful, the solution proposed with $a = array_combine($a, $a); will not work for numeric values.
I for example wanted to have a memory array(128,256,512,1024,2048,4096,8192,16384) to be the keys as well as the values however PHP manual states:
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
So I solved it like this:
foreach($array as $key => $val) {
$new_array[$val]=$val;
}

Adding elements to array as sub-elements dynamically in PHP [duplicate]

This question already has answers here:
Using a string path to set nested array data [duplicate]
(8 answers)
Closed 2 years ago.
I want to find a workaround for the following problem:
I have n vectors(unique), like the following: ("val1", "val2", "val3", ..., "valn" ).
Each vector's length is different.
I want to add any of those in a new array, but using the vector values(val1,val2,val3) elements as sub-elements recursively for the new array, taken from the main vector(val1 => val+1 => val+2 => val+3 => ... val+n => solution), and the last element of the vector is an integer or a string(not a sub-array/vector as the others), which will match with the last element of the new array, and it's new array's soluton/target.
The workaround solution I am applying right now is this:
Let's suppose the target(solution) is the end value of the array(an integer or string).
In this case I suppose to work on a vector with 4 elements, where the last one is the solution.
$vector = array("val1", "val2", "val3", "target");
$count = count($vector);
$new_array = array();
switch($count){
case 1:
....
case 4:
$new_array[$vector[0]][$vector[1]][$vector[2]] = $vector[3];
/*New array will be
$new_array = [
val1 =>
val2 =>
val3 => "target"
];
*/
break;
}
The vectors I am using are many and with different sizes, so the solution/target can be in the 1st element, second, third and so on, so I applied in my switch any cases from 0 to 5 for example, working as wrote above.
I think there could be a better solution, to loop inside a for(or better, a while) cycle
But I am currently having no ideas on how it should be, and I didn't find any workaround in the web.
Does anyone have a soluton for this?
Thanks in advance
You can build the resulting array starting from the most recent nested element:
$vector = array("val1", "val2", "val3", "val4", "val5", "target");
$new_array = array_pop($vector);
foreach(array_reverse($vector) as $val) {
$new_array = [$val => $new_array];
}
print_r($new_array);
Hi You can change your code like it:
<?php
$vector = array("val1", "val2", "val3", "val4", "val5", "target");
$count = count($vector);
$new_array = array();
$new_array[$vector[$count - 2]] = $vector[$count - 1];
for ($i=($count - 3); $i >= 0; $i--) {
$temp_array = array();
$temp_array[$vector[$i]] = $new_array;
$new_array = $temp_array;
}
print_r($new_array);
And the result will be like it:
Array
(
[val1] => Array
(
[val2] => Array
(
[val3] => Array
(
[val4] => Array
(
[val5] => target
)
)
)
)
)

Moving first value and key to the end on an array [duplicate]

This question already has answers here:
How do I move an array element with a known key to the end of an array in PHP?
(4 answers)
Closed 4 years ago.
I have an array that looks something like this:
'array_1' => [
'A' => 'A', 'B' => 'B', 'C' => 'C',
],
I need to shift the first value and key to the end of the array, so it should look like this:
'array_1' => [
'B' => 'B', 'C' => 'C', 'A' => 'A',
],
I've tried to do it like this:
array_push($arr, array_shift($arr));
But the result is this:
'array_1' => [
'B' => 'B', 'C' => 'C', '0' => 'A',
],
The key for value A changed to 0 but i need it ro remain A. Any suggestions?
array_push does not allow you to enter a key.
Therefore you have to use
$arr['key'] = value
First, do a reset(array). This reset the internal pointer to point at the first element
So that when you use key($arr), it will return the first key.
Then use array_shift() to get the first value in the array
Code:
reset($arr)
$arr[key($arr)] = array_shift($arr);
array_push($arr, array_shift($arr));
This removes the first VALUE of $arr, and then adds it to the end of the array as a value, therefore with a numeric key. Since there are no extant numeric keys, it is assigned key 0. Hence your result.
You need to extract the first pair, and push that:
reset($arr);
list($k, $v) = each($arr);
array_shift($arr);
$arr[$k] = $v;
That said... if you're relying on non-numeric key order (or mixed numeric/non-numeric keys), then I fear that your design might be flawed.
A keypair array (a dictionary, or sometimes hash or map) has no key order in most languages and even several representations (most notably, JSON - even if most JSON libraries usually maintain insertion order). Assuming it has might be setting oneself up for a fall.

What does a JSON array look like in PHP? [duplicate]

This question already has answers here:
Retrieving array keys from JSON input
(7 answers)
Closed 8 years ago.
I have created a simple json string to decode into a data array, but I am very confused about how to iterate through the array once it is decoded:
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$data = json_decode($json, true);
for ($j = 0; $j < count($data); $j++) {
echo "$j: $data[$j]<br>";
}
?>
I can't seem to get this code to work because it is saying that every offset is undefined, so I think the trouble stems from my understanding of what an array looks like once it has been decoded.
When I do a var_dump(json_decode($json, true)), I get this result:
array (size=5)
'a' => int 1
'b' => int 2
'c' => int 3
'd' => int 4
'e' => int 5
So what does this mean exactly? Are the array indexes 'a', 'b', 'c', 'd', and 'e' respectively? If so, then how can I iterate through each of these to print out all of their values?
Arrays in PHP are not the same as arrays in JavaScript (or Json). However, what you're looking at here:
{"a":1,"b":2,"c":3,"d":4,"e":5}
Is not actually a Json array, but a Json object. a, b, c, d, and e are properties of that object (which are a bit like indexes in a PHP array).
To iterate through the properties of this object, you can use a foreach loop:
$data = json_decode($json, true);
foreach ($data as $key => $value) {
echo "$key: $value<br>";
}

Somewhat efficient way to append array 1 to array 2, while preserving the numeric keys of array 2, and adding keys n through n + x to array 1?

This is sort of two questions, but there may be one overall answer for the whole problem. I have an array that I need to append onto another array. Both arrays must have specific numeric keys. My problems are:
I need the numeric keys for the array that I am appending onto to be preserved.
array_splice() and array_merge() won't work to join the arrays because numeric keys in both arrays will be reset.
I need to make the keys of the newly added elements to be n through n + x, meaning if n is 100 and x is 25, the keys for the newly added elements should be 100 through 125.
Can anyone think of a somewhat efficient way of doing this?
EDIT
For anyone curious, found a better way of adding the correct keys to the array.
// add correct keys
$array_segment = array_combine(range($offset, $offset + count($array_segment) - 1), $array_segment);
// merge arrays while maintaining keys
$first_array = $first_array + $array_segment;
I think this is a very simple solution but, if I understand well what you want, it works and it's fast. In my opinion you can use this approach:
$array1 = array(1 => 'a', 2 => 'b', 3 => 'c');
$array2 = array(4 => 'd', 5 => 'e', 6 => 'f');
foreach($array2 as $key => $value)
$array1[$key] = $value;
var_dump($array1);
$array1[] = 'g';
$array1[] = 'h';
var_dump($array1);
You can see the result here:
http://codepad.org/ogD9drpK
Another way which will avoid the foreach is to execute this instruction:
// avoid the loop
//foreach($array2 as $key => $value)
// $array1[$key] = $value;
$array1 += $array2;
You can see the result here:
http://codepad.org/cZxCfRn6

Categories