I am having two arrays with the same key . How can I combine those two arrays without overwriting the keys of first array.
I tried using array_merge() function , + operation
These are the two arrays:
Array ( [1] => 1 ) Array ( [1] => 0 )
I want the output to be like
array( [1] => 1 , [1] => 0)
You can't have duplicate keys in an array.
What you can do is build an array of object with different keys: 0,1,2,3,4,etc. but with sub objects which will make access to the same object property.
// for istance in this case you end up having an array
// with 5 objects with a property named "key" with a value
$arrayOfObjects = [];
$arrayOfObjects[] = (object)["key"=>"value0"];
$arrayOfObjects[] = (object)["key"=>"value1"];
$arrayOfObjects[] = (object)["key"=>"value2"];
$arrayOfObjects[] = (object)["key"=>"value3"];
$arrayOfObjects[] = (object)["key"=>"value4"];
// to return the value $arrayOfObjects[4]->key
Related
I'm working with multi-dimensional arrays in PHP. I want to store two string values in a two dimensional array. I have tried the following code:
$arr[][]=['string1']['string2'];
I have also tried:
$arr[][]="string1","string2";
Due to the comma I have a syntax error.
How can I fix this?
$arr = [];
$arr[] = ['string1'];
$arr[] = ['string2'];
// or simply
// $arr = [['string1'], ['string2']];
print_r($arr);
// output:
Array ( [0] => Array ( [0] => string1 ) [1] => Array ( [0] => string2 ) )
If you want 'string1' and 'string2' to be the key and subkey in an array then you use:
$arr = [];
$arr['string1']['string2'] = 'somevalue';
I have this dynamic multiple arrays that I need to combine in one array and serialized them. The problem is I need to keep both key and value.
$arr = array($bet_option_id => $bet_option_name);
Here i need to keep both bet_option_id AND bet_option_name. Then this result output:
Array ( [997650802] => Over 2.5 )
Array ( [997650807] => Yes )
This need to be simply
Array
(
[997650802] => Over 2.5
[997650807] => Yes
)
As it's dynamic, sometimes not comes with just single array so apparently I couldn't get it working. I need to retrieve both bet_option_id & bet_option_name. Tried something like this:
$arr = array($bet_option_id => $bet_option_name); //This is where all array keys, values are stores
$result = array();
foreach ($arr as $array) {
$result = array_merge($result, $array);
}
Any inputs will be nice.
Rather than create individual arrays like...
$arr = array($bet_option_id => $bet_option_name);
If you first create an empty array ( like you do with $result)
$arr = array();
and then add each item in using
$arr[$bet_option_id] = $bet_option_name;
Then you don't need to manipulate the array after - just create it as you want it in the first place.
You could either do like Nigel Ren suggested which is the most elegant solution
In case that you do not have arrays that their keys are entirely numeric you may use array_merge. The quote following is from PHP array-merge
Example #2 Simple array_merge() example
$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);
Don't forget that numeric keys will be renumbered!
Array
(
[0] => data
)
Alternatively you can always join arrays together like this
$a1 = [ 997650802 => 'Over 2.5' ];
$a2 = [ 997650807 => 'Yes' ];
var_dump( $a1 + $a2 ); // result is [997650802 => 'Over 2.5',997650807 => 'Yes']
You can check more about Array Types and Array Operators
I have an array named $arr = array. Some of its keys has value, like this:
$arr['1'] = 'one';
$arr['2'] = 'two';
$arr['3'] = 'three';
Now I initialize that array with another arry, some thing like this:
$arr = array('4' => 'four', '5' => 'five');
But I need to keep the previous values. I mean is, when I print that array, the output will be like this:
echo '<pre>';
print_r($arr);
/* ---- output:
Array
(
[4] => four
[5] => five
)
*/
While I want this output:
Array
(
[1] => one
[2] => two
[3] => three
[4] => four
[5] => five
)
So, How can I take care of old keys (values) after re-initialized?
Here are your options detailed below: array_merge, union (+ operator), array_push, just set the keys directly and make a function that just loops over the array with your own custom rules.
Sample data:
$test1 = array('1'=>'one', '2'=>'two', '3'=>'three', 'stringkey'=>'string');
$test2 = array('3'=>'new three', '4'=>'four', '5'=>'five', 'stringkey'=>'new string');
array_merge (as seen in other answers) will re-index numeric keys (even numeric strings) back to zero and append new numeric indexes to the end. Non numeric string indexes will overwrite the value where the index exists in the former array with the value of the latter array.
$combined = array_merge($test1, $test2);
Result (http://codepad.viper-7.com/c9QiPe):
Array
(
[0] => one
[1] => two
[2] => three
[stringkey] => new string
[3] => new three
[4] => four
[5] => five
)
A union will combine the arrays but both string and numeric keys will be handled the same. New indexes will be added and existing indexes will NOT be overwritten.
$combined = $test1 + $test2;
Result (http://codepad.viper-7.com/8z5g26):
Array
(
[1] => one
[2] => two
[3] => three
[stringkey] => string
[4] => four
[5] => five
)
array_push allows you to append keys to an array. So as long as the new keys are numeric and in sequential order, you can push on to the end of the array. Note though, non-numeric string keys in the latter array will be re-indexed to the highest numeric index in the existing array +1. If there are no numeric keys, this would be zero. You would also need to reference each new value as a separate argument (see arguments two and three below). Also, since the first argument is taken in by reference, it will modify the original array. The other options allow you to combine to a separate array in case you need the original.
array_push($test1, 'four', 'five');
Result (http://codepad.viper-7.com/5b9nvC):
Array
(
[1] => one
[2] => two
[3] => three
[stringkey] => string
[4] => four
[5] => five
)
You could also just set the keys directly.
$test1['4'] = 'four';
$test1['5'] = 'five';
Or even just make a loop and wrap it in a function to handle your custom rules for merging
function custom_array_merge($arr1, $arr2){
//loop over array 2
foreach($arr2 as $k=>$v){
//if key exists in array 1
if(array_key_exists($arr1, $k)){
//do something special for when key exists
} else {
//do something special for when key doesn't exists
$arr1[$k] = $v;
}
}
return $arr1;
}
The function could be expanded to use stuff like func_get_args to allow any number of arguments.
I'm sure there are also more "hacky" ways to do it using stuff like array_
splice or other array functions. However, IMO, I would avoid them just to keep the code a little more clear about what you are doing.
use array_merge:
$arr = array_merge($arr, array('4' => 'four', '5' => 'five'));
Well, as per the comments (which are correct) this will reindex the array, another solution to avoid that would be to do as follows:
array_push($arr, "four", "five");
But this would not work if you have different keys, like strings that are not masked numbers.
Another way is to use + in order to merge them maintaining keys:
$arr['1'] = 'one';
$arr['2'] = 'two';
$arr['3'] = 'three';
$arr2 = array('4' => 'four', '5' => 'five');
$arr = $arr + $arr2;
Another way to do it, and keeps the keys of the array, is using array_replace.
$arr['1'] = 'one';
$arr['2'] = 'two';
$arr['3'] = 'three';
print_r(array_replace($arr, array('4' => 'four', '5' => 'five')));
Output:
Array
(
[1] => one
[2] => two
[3] => three
[4] => four
[5] => five
)
i am trying to compare two arrays using php intersect function.
I am using following code
$input_array=array();
$input_array=explode("," , $_POST['list']);
$array = array();
$result1 =mysql_query("SELECT b_no FROM abc");
while($fetch_array=mysql_fetch_array($result1)){
$array[] = $fetch_array['b_no'];
}
$result=array_intersect($input_array,$array);
echo"<pre>";
print_r($result);
echo"</pre>";
and result is like this:
Array
(
[4] => 443829
[5] => 952040
)
The resultant array have not their own indexing. Is possible to provide indexing?
It is possible to provide indexing, but you will need to specify which indexing you want.
If the resulting indexing is not what you expected, please note that array_intersect() only compares the values of each array, and it retains the index or key from the first array of each match.
If your requirement is to also match on the keys of an associative array (although I am inferring you are not judging from your example) you can use array_intersect_assoc().
If you want to simply 'reset' the indexing you can use array_values(). For example:
<?php
$a = [2 => 1, 2, 3];
$b = [2, 3, 4];
$intersect = array_intersect($a, $b);
print_r($intersect);
// Original keys are retained:
//
// Array
// (
// [3] => 2
// [4] => 3
// )
print_r(array_values($intersect));
// Original keys are discarded:
//
// Array
// (
// [0] => 2
// [1] => 3
// )
On the other hand, if you had a specific set of keys you wanted to use, say for example ['foo', 'bar'] you can use array_combine() - it accepts two arrays, one as keys and the other as values, to explicitly define a new set of indexes or keys for an array. For example:
$keys = ['foo', 'bar'];
print_r(array_combine($keys, $intersect);
// Array
// (
// [foo] => 2
// [bar] => 3
// )
$indexes = [100, 200];
print_r(array_combine($indexes, $intersect));
// Array
// (
// [100] => 2
// [200] => 3
// )
Please note, array_combine() requires that the length of both arrays are the same. I cannot really provide any more detail unless you update your question but I hope this helps :)
I have 2 api end points that load JSON data...
1. subject matter experts
Array
(
[0] => Array
(
[ExpertiseId] => 1
[IndustryId] => 1
[PersonId] => 3
)
...
)
people database
Array
(
[0] => Array
(
[Id] => 1
[Name] => Joe
[Office] => New York
)
....
)
I'd like to pass both functions into an array, specify to merge on [matter.PersonId] => [people.Id] so the returned array would become
Array
(
[0] => Array
(
[ExpertiseId] => 1
[IndustryId] => 1
[PersonId] => 3
[Id] => 1
[Name] => Joe
[Office] => New York
)
...
)
You have to iterate over both arrays and reorganize the data in such a way that merging can happen. In practice that means rekeying the first array by PersonId and the second by Id; this is very easy to do with array_column:
$matter = array_column($matter, null, 'PersonId');
$people = array_column($people, null, 'Id');
At this point only a simple task is left: merging the items (arrays) that share the same key in both $matter and $people.
In a perfect world that would be an one-liner with array_merge_recursive, but that function does not actually merge arrays that have integer keys like these (the ids we used as keys are integers). So a little standard iteration is in order: pick one of the arrays and merge its contents with the other:
foreach ($people as $id => $data) {
// If there's a guarantee that both arrays will definitely have the same
// set of keys (ids) so that $matter[$id] is guaranteed to exist,
// you can also use the simpler: $matter[$id] += $data
$matter[$id] = isset($matter[id]) ? $matter[$id] + $data : $data;
}
...and now $matter has all the data merged together.
Try array_merge()
$newArray = array_merge(first_array, second_array);