Insert key and value into array - php

I have this code
$array = array('o' => 'one', 't' => 'three', 'f' => 'four');
array_push($array, array('s' => 'six'));
print_r($array);
that insert new key and value into the array , but when i print the new $array it returned this
Array ( [o] => one [t] => three [f] => four [0] => Array ( [s] => six ) )
i need to return like this
Array ( [o] => one [t] => three [f] => four [s] => six )
how to remove [0] => Array () from the array ?

array_push is intended for lists.
$arr = array(5, 6, 7);
array_push($arr, 8); // array(5, 6, 7, 8);
You can add elements to arrays in many ways, this is one:
$array = array('o' => 'one', 't' => 'three', 'f' => 'four');
$array["s"] = "six";
Here is another:
$array = array_merge($array, array("s" => "six"));
PHP treats lists like array(1, 2, 3); differently than associative arrays like array("foo" => "bar");. The differences are minor, but they show up with functions like array_push.

Related

Zip multiple arrays in PHP based on their identical keys and not their indices or their positions in array

I have two arrays:
$a = ['one'=>1,'two'=> 2,'three'=> 3,'four'=> 4,'five'=> 5, 'six' => 6];
$b = ['one'=>'uno', 'three'=>'tres','two'=> 'dos', 'four'=>'cuatro', 'five'=>'cinco'];
note that in $b Array 'three' and 'two' keys are not in same order as $a. also 'six' key is not available in $b Array.
I want this result as output:
Array
(
[0] => Array
(
[0] => 1
[1] => uno
)
[1] => Array
(
[0] => 2
[1] => dos
)
[2] => Array
(
[0] => 3
[1] => tres
)
[3] => Array
(
[0] => 4
[1] => cuatro
)
[4] => Array
(
[0] => 5
[1] => cinco
)
)
I tried to use array_map but it don't detect keys and just zip them based of their indices:
$d = array_map(null, $a, $b);
Can't you just use ksort(). Then, create a new array using `foreach'?
An example using foreach
<?php
$a = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5];
$b = ['one' => 'uno', 'three' => 'tres', 'two' => 'dos', 'four' => 'cuatro', 'five' => 'cinco'];
$output = [];
foreach ($a as $key => $value) {
$output[] = [$value, $b[$key]];
}
print_r($output);
modified ikhvjs answer (when keys in both arrays are not same as each others):
$a = ['one' => 1, 'two' => 2, 'four' => 4, 'five' => 5, 'six' => 6];
$b = ['one' => 'uno', 'three' => 'tres', 'two' => 'dos', 'four' => 'cuatro', 'five' => 'cinco'];
$r=array_intersect_key($a,$b);
$output = [];
foreach ($r as $key => $value) {
$output[] = [$value, $b[$key]];
}
echo "<pre>";
print_r($output);
echo "</pre>";
I must say #ikhvjs's answer is the closest to perfect, but the $b array doesn't have a value with the key six. To accommodate the possibility of elements in $b not relating to elements in $a, use the null coalescing operator to fallback to a null value.
As for the mentioning of ksort(), this will do nothing to accommodate the fact that the input arrays have different lengths / keys.
The use of array_intersect_key() will result in $a values being omitted where not related to an element in $b.
If $a is not a reliable "master" array (with all possible keys), then you will need to loop a temporary array formed by merging the two arrays and implement the null coalescing operator on both values to be pushed into the result array.
Code: (Demo) (Demo of null coalescing on both values)
$a = [
'one' => 1,
'two' => 2,
'three' => 3,
'four' => 4,
'five' => 5,
'six' => 6
];
$b = [
'one' => 'uno',
'three' => 'tres',
'two' => 'dos',
'four' => 'cuatro',
'five' => 'cinco'
];
$result = [];
foreach ($a as $k => $v) {
$result[] = [$v, $b[$k] ?? null];
}
var_export($result);
Output:
array (
0 =>
array (
0 => 1,
1 => 'uno',
),
1 =>
array (
0 => 2,
1 => 'dos',
),
2 =>
array (
0 => 3,
1 => 'tres',
),
3 =>
array (
0 => 4,
1 => 'cuatro',
),
4 =>
array (
0 => 5,
1 => 'cinco',
),
5 =>
array (
0 => 6,
1 => NULL,
),
)

php: combine multiple arrays value into one array preserving keys

I have multiple arrays structured like these:
$array1 = ["aaa" => 1, "bbb" => 1];
$array2 = ["aaa" => 12, "bbb" => 12];
$array3 = ["bbb" => 15, "ccc" => 15];
meaning:
every array has the same value for each key (eg: array1 has value "1" for every item in the array) but there are no arrays sharing the same value (eg: if array1 has value 1, then none of the other arrays has value = 1)
the arrays may or may not share the same keys
I need to combine these arrays in a way that the final result is something like this:
$result = [
"aaa" => [1,12],
"bbb" => [1,12,15],
"ccc" => [15],
];
meaning:
the final array must contain all the keys from the previous arrays
the value of the key is an array composed of all the values of the previous arrays that shared the same key
I know it's a bit messy, but I hope it is clear enough. I'm struggling to build the $result array. I tried merge, combine, intersect, but none of them seems to work. Is there a way to build the $result array without using a loop?
Thanks
Does it match your goal ?
<?php
$array1 = ["aaa" => 1, "bbb" => 1];
$array2 = ["aaa" => 12, "bbb" => 12];
$array3 = ["bbb" => 15, "ccc" => 15];
$array = array_merge_recursive($array1, $array2, $array3);
print_r($array);
?>
outputs
Array
(
[aaa] => Array
(
[0] => 1
[1] => 12
)
[bbb] => Array
(
[0] => 1
[1] => 12
[2] => 15
)
[ccc] => 15
)
Merge all of array into an mergedArray. Then use 2 foreach to set it.
<?php
$array1 = ["aaa" => 1, "bbb" => 1];
$array2 = ["aaa" => 12, "bbb" => 12];
$array3 = ["bbb" => 15, "ccc" => 15];
$mergedArray = [$array1, $array2, $array3];
$result = [];
foreach ($mergedArray as $array) {
foreach ($array as $key => $item) {
$result[$key][] = $item;
}
}
echo '<pre>';
print_r($result);
echo '</pre>';
exit;
?>
The result:
Array
(
[aaa] => Array
(
[0] => 1
[1] => 12
)
[bbb] => Array
(
[0] => 1
[1] => 12
[2] => 15
)
[ccc] => Array
(
[0] => 15
)
)

Consolidate differently structured arrays into one without rearranging keys or values

I have a page that has 4 widgets each getting data from the database. Each widgets gets data in different formats since i have a table widget, a statistics widget and a widget with just one value.
Supposing i have the results of queries returning data say in this format
$arr1 = array(1, 3, 5);
$arr2 = array(2, 4, 6);
$test1 = array(
'11' => '11',
'22' => '22',
'33' => '33',
'44' => '44'
);
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
how can i pass the arrays as json encoded as one but retains their array structure on the client side for easier and faster creating on widget views?.
I have looked at array_merge and according to the docs, that's not what i am looking for.
how can i pass the arrays as json encoded as one but retains their array structure on the client side for easier and faster creating on widget views?.
You might arrange each array to be json encoded together like so:
$bundle = json_encode([$arr1, $arr2, $test1, $array1, $array2]);
Result:
[[1,3,5],[2,4,6],{"11":"11","22":"22","33":"33","44":"44"},{"0":"zero_a","2":"two_a","3":"three_a"},{"1":"one_b","3":"three_b","4":"four_b"}]
If I understood your issue correctly, you can assign your arrays to a multidimensional array.
Based in your example:
$dataArray = [];
$arr1 = array(1, 3, 5);
$arr2 = array(2, 4, 6);
$dataArray['data_type_one'][] = $arr1;
$dataArray['data_type_one'][] = $arr2;
$test1 = array(
'11' => '11',
'22' => '22',
'33' => '33',
'44' => '44'
);
$dataArray['data_type_two'] = $test;
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
$dataArray['data_type_three'][] = $array1;
$dataArray['data_type_three'][] = $array2;
You will end up with this array structure:
Array
(
[data_type_one] => Array
(
[0] => Array
(
[0] => 1
[1] => 3
[2] => 5
)
[1] => Array
(
[0] => 2
[1] => 4
[2] => 6
)
)
[data_type_two] => Array
(
[11] => 11
[22] => 22
[33] => 33
[44] => 44
)
[data_type_three] => Array
(
[0] => Array
(
[0] => zero_a
[2] => two_a
[3] => three_a
)
[1] => Array
(
[1] => one_b
[3] => three_b
[4] => four_b
)
)
)
Then, in your views, you can do whatever you need:
foreach ($arrayData['data_type_one'] as $someData) {
echo $someData[0] . ' ';
//will print 1 2
}
echo $dataArray['data_type_two']['11'];
//will print 11

How to merge array and preserve keys?

I have two arrays:
$array1 = array('a' => 1, 'b' => 2, 'c' => 3);
$array2 = array('d' => 4, 'e' => 5, 'f' => 6, 'a' => 'new value', '123' => 456);
I want to merge them and keep the keys and the order and not re-index!!
How to get like this?
Array
(
[a] => new value
[b] => 2
[c] => 3
[d] => 4
[e] => 5
[f] => 6
[123] => 456
)
I try to array_merge() but it will not be preserved the keys:
print_r(array_merge($array1, $array2));
Array
(
[a] => 'new value'
[b] => 2
[c] => 3
[d] => 4
[e] => 5
[f] => 6
[0] => 456
)
I try to the union operator but it will not overwriting that element:
print_r($array1 + $array2);
Array
(
[a] => 1 <-- not overwriting
[b] => 2
[c] => 3
[d] => 4
[e] => 5
[f] => 6
[123] => 456
)
I try to swapped place but the order is wrong, not my need:
print_r($array2 + $array1);
Array
(
[d] => 4
[e] => 5
[f] => 6
[a] => new value
[123] => 456
[b] => 2
[c] => 3
)
I dont want to use a loop, is there a way for high performance?
You're looking for array_replace():
$array1 = array('a' => 1, 'b' => 2, 'c' => 3);
$array2 = array('d' => 4, 'e' => 5, 'f' => 6, 'a' => 'new value', '123' => 456);
print_r(array_replace($array1, $array2));
Available since PHP 5.3.
Update
You can also use the union array operator; it works for older versions and might actually be faster too:
print_r($array2 + $array1);
Let suppose we have 3 arrays as below.
$a = array(0=>['label'=>'Monday','is_open'=>1],1=>['label'=>'Tuesday','is_open'=>0]);
$b = array(0=>['open_time'=>'10:00'],1=>['open_time'=>'12:00']);
$c = array(0=>['close_time'=>'18:00'],1=>['close_time'=>'22:00']);
Now, if you want to merge all these array and want a final array that have all array's data under key 0 in 0 and 1 in 1 key as so on.
Then you need to use array_replace_recursive PHP function, as below.
$final_arr = array_replace_recursive($a, $b , $c);
The result of this will be as below.
Array
(
[0] => Array
(
[label] => Monday
[is_open] => 1
[open_time] => 10:00
[close_time] => 18:00
)
[1] => Array
(
[label] => Tuesday
[is_open] => 0
[open_time] => 12:00
[close_time] => 22:00
)
)
Hope the solution above, will best fit your requirement!!
#Jack uncovered the native function that would do this but since it is only available in php 5.3 and above this should work to emulate this functionality on pre 5.3 installs
if(!function_exists("array_replace")){
function array_replace(){
$args = func_get_args();
$ret = array_shift($args);
foreach($args as $arg){
foreach($arg as $k=>$v){
$ret[(string)$k] = $v;
}
}
return $ret;
}
}
array_replace_recursive() or array_replace() is the function you are looking for
$array1 = array('a' => 1, 'b' => 2, 'c' => 3);
$array2 = array('d' => 4, 'e' => 5, 'f' => 6, 'a' => 'new value', '123' => 456);
var_dump(array_replace_recursive($array1, $array2));
Demo
I think this might help if i understand properly:
foreach ($i = 0, $num = count($array2); $i < $num; $i++)
{
$array = array_merge($array1, $arrar2[$i]);
}

Merging associate arrays in PHP

I have a serialized array stored in a cookie, at one point in my application I need to merge this array with another array with the same design, so:
Array 1:
$arr1 = array(
"user_id" => 1,
"item_id" => 2,
"quant" => 3
);
I set this in a cookie with:
serialize($arr1);
Array 2:
$arr2 = array(
"user_id" => 5,
"item_id" => 5,
"quant" => 6
);
My attempt at merging the two arrays:
First I unserialize the first array value that is in my cookie, followed by a merge with the second array
$un_arr1 = unserialize($cookie_val);
$final = array_merge($arr2, $un_arr1);
This is returning me only the values from the first array though.
What I am trying to achieve:
Array
(
[0] => Array
(
[user_id] => 1
[item_id] => 2
[quant] => 3
)
[1] => Array
(
[user_id] => 4
[item_id] => 5
[quant] => 6
)
)
$final = array($array1, $array2);
You are looking for array_merge_recursive instead of array_merge.
<?php
$A = array('a' => 1, 'b' => 2, 'c' => 3);
$B = array('c' => 4, 'd'=> 5);
$result = array_merge_recursive($A, $B);
print_r($result);
See it in action.

Categories