i have two array and i want to make unique array with single array
for example i have $a=array(3); and $b=array(1,2,3) so i want $c=array(1,2,3)
i made a code like:
$a=array(3);
$b=explode(',','1,2,3');
$ab=$a+$b;
$c=array_unique ($ab);
print_r($c);
it gives me Array ( [0] => 3 [1] => 2 )
but i want to Array ( [0] => 1 [1] => 2 [2] => 3 )
$a = array(1,2,3,4,5,6);
$b = array(6,7,8,2,3);
$c = array_merge($a, $b);
$c = array_unique($c);
The operation
$ab = $a + $b
Is giving you a result you did not expect. The reason for this behaviour has been explained previously at PHP: Adding arrays together
$ab is Array ( [0] => 3 [1] => 2 [2] => 3 )
The + operator appends elements of remaining keys from the right
handed array to the left handed, whereas duplicated keys are NOT
overwritten.
array_merge provides a more intuitive behaviour.
Array merge, man. Array merge.
Anyway, as this answer for similar question ( https://stackoverflow.com/a/2811849/223668 ) tells us:
The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten.
If you have numeric keys (as in standard tables), they are for for sure duplicate in both arrays and the result is far from desired.
So the code should look like that:
$c = array_unique(array_merge($a, $b));
You need to use this array_merge to concat two array.
http://www.php.net/manual/en/function.array-merge.php
not
$ab = $a + $b
Related
This question already has answers here:
Move array item with certain key to the first position in an array, PHP
(9 answers)
move array element to the first position but remain order
(4 answers)
Move an array element to a new index in PHP
(9 answers)
Move Value in PHP Array to the Beginning of the Array
(12 answers)
Move array element with a particular value to top of array
(2 answers)
Closed 2 months ago.
How to sort an array at PHP to force selected row as a first ?
My array is
array[]=array(id=>'a', content=>'lemon');
array[]=array(id=>'b', content=>'apple');
array[]=array(id=>'c', content=>'banana');
array[]=array(id=>'d', content=>'cherry');
How to sort the array to force
array[]=array(id=>'b', content=>'apple');
as a first row and doesn't matter the rest (apple is the key).
And in other example turn sort to get
array[]=array(id=>'d', content=>'cherry');
as a first row and doesn't matter the rest (cherry is the key).
Another way to do this is to effectively rotate the array using array_slice, bringing the element you want to the start:
$first = 'apple';
$k = array_search($first, array_column($array, 'content'));
$array = array_merge(array_slice($array, $k), array_slice($array, 0, $k));
print_r($array);
Output:
Array (
[0] => Array ( [id] => b [content] => apple )
[1] => Array ( [id] => c [content] => banana )
[2] => Array ( [id] => d [content] => cherry )
[3] => Array ( [id] => a [content] => lemon )
)
Demo on 3v4l.org
There are 2 ways I can think of doing this. The first is as Ultimater in the comments suggest to extract the matching row, then sort and then add the row back in...
$first = 'apple';
$array = [];
$array[]=array('id'=>'a', 'content'=>'lemon');
$array[]=array('id'=>'b', 'content'=>'apple');
$array[]=array('id'=>'c', 'content'=>'banana');
$array[]=array('id'=>'d', 'content'=>'chery');
$firstElement = array_search($first, array_column($array, "content"));
$row = $array[$firstElement];
unset($array[$firstElement]);
sort($array);
array_unshift($array, $row);
print_r($array);
The second is to use usort and add specific clauses in that if the key matches the row you want first, then it will always force it to the first row...
$first = 'apple';
usort($array, function ($a, $b) use ($first){
if ( $a['content'] == $first) {
return -1;
}
if ( $b['content'] == $first) {
return 1;
}
return $a <=> $b;
});
print_r($array);
(I've used <=> in this which is PHP 7+, there are alternatives if you need to use PHP 5).
If as your comment suggests that there is no need to sort the rest of the data, then the first set of code minus the sort() should do.
One other option - if id:content is one to one, we can index the array by content and merge with an array with a single empty "apple" key (or whichever content value you're looking for).
$array = array_merge(['apple' => []], array_column($array, null, 'content'));
If the resulting string keys are undesirable the array can be reindexed with array_values.
If the array only contains id and content and id:content is in fact one to one, a "dictionary" of key-value pairs will be handier to deal with than a list of rows like this and it would probably be better to set the array up that way to begin with if possible.
If id:content is not one to one, then... never mind. ;-)
I am trying to separate an array into two separate arrays. For example, if I have an array like this
Array([0]=>Hello[1]=>I'm[2]=>Cam)
I want to split it into two arrays and add another string
Array1([0]=>Hello[1]=>There,)
Array2([0]=>I'm[1]=>Cam)
Then finally add the two together
Array([0]=>Hello[1]=>There,[2]=>I'm[3]=>Cam)
What would be the simplest way to do this?
I know I can use array merge to put the two together but I don't know how to separate them at a certain point.
I'm also doing this on a large file that will be constantly getting bigger, so I cant use array_chunk()
Looking at your end result goal, I think a shorter method to get your desired response is to use array_splice which lets you insert into a middle of an array....
$arrayVarOriginal = array('Hello', 'Im', 'Cam');
$arrayVarExtra = array('There');
array_splice($arrayVarOriginal, 1, 0, $arrayVarExtra);
This should send you back Array([0]=>Hello[1]=>There,[2]=>Im[3]=>Cam) like you wanted!
The above avoids having to split up the array.
HOWEVER
If you did want to do it the hard way, here is how you would...
$arrayVarOriginal = array('Hello', 'Im', 'Cam');
$array1stPart = array(arrayVarOriginal[0], 'There');
$array2ndPart = array_shift($array1stPart);
$finalArray = array_merge($array1stPart, $array2ndPart);
How? array_shift removes the first item from any array, so that how we get $array2ndPart.... and $array1stPart is even easier as we can just manually build up a brand new array and take the first item from $arrayVarOriginal which is at position 0 and add 'There' in as our own new position 1.
Hope that helps :)
array_shift, array_splice, and array_merge are what you need to look into.
Based from your question, here step-by-step to get what you want for your final output.
1) Split Array
$arr = array('Hello', 'I\'m', 'Cam');
$slice = count($arr) - 1;
$arr1 = array_slice($arr, 0, -$slice);
$arr2 = array_slice($arr,1);
so, you get two new array here $arr1 and $arr2
2) Add new string
$arr1[] = "There";
3) Finally, combine the array
$arr = array_merge($arr1, $arr2)
Here sample output when you print_r the $arr
Array
(
[0] => Hello
[1] => There
[2] => I'm
[3] => Cam
)
array_slice second parameter is position where you want split. So you can do this dynamically by count the array length.
$string = array("Hello","I'm","Cam");
$firstArray = array_slice($string ,0,1);
array_push($firstArray,"There,");
$secondArray = array_slice($string ,1,2);
echo "<pre>";
print_r($firstArray);
echo "==========="."<pre>";
print_r($secondArray);
echo "<pre>";
print_r(array_merge($firstArray,$secondArray));
//out put
Array
(
[0] => Hello
[1] => There,
)
===========
Array
(
[0] => I'm
[1] => Cam
)
Array
(
[0] => Hello
[1] => There,
[2] => I'm
[3] => Cam
)
Hope it will be worked for your requirement. If not or you need more specify regarding this you can clarify your need.
I have two dynamic associated array and I am trying to merge them into one array BUT I need to keep the original keys as the orginal arrays but in return I am getting [0] for A which I need to keep it [1] as it was in array $a
$a = ["1"=>"A", "2"=>"B", "3"=>"C"];
$b = ["n"=>"5"];
$c = array_merge($a,$b);
print_r($c);
Array (
[0] => A
[1] => B
[2] => C
[n] => 5 )
In order to preserve keys of your array you need to use + operator over here like as
$a = ["1"=>"A", "2"=>"B", "3"=>"C"];
$b = ["n"=>"5"];
$c = $a + $b;
print_r($c);
You can check PHP Manuals Example #2 Simple array_merge() example
i am not a php developer. so there could be better answers out there
the php documentation says that numerical keys are new numbered. i think that even a string as key with a nummeric value is interpretet as number.
can you try this (not the added 'a' on the nummeric keys):
$a = ["1a"=>"A", "2a"=>"B", "3a"=>"C"];
$b = ["n"=>"5"];
$c = array_merge($a,$b);
print_r($c);
it is not clean code, but after this you can "remove" the 'a' and you have your numeric key
$result = array(
0=>array('a'=>1,'b'=>'Hello'),
1=>array('a'=>1,'b'=>'other'),
2=>array('a'=>1,'b'=>'other'),
);
If it is duplicated removed it, so the result is as follows:
$result = array(
0=>array('a'=>1,'b'=>'Hello'),
1=>array('a'=>1,'b'=>'other')
);
Could any know to do this?
Thanks
Regardless what others are offering here, you are looking for a function called array_uniqueDocs. The important thing here is to set the second parameter to SORT_REGULAR and then the job is easy:
array_unique($result, SORT_REGULAR);
The meaning of the SORT_REGULAR flag is:
compare items normally (don't change types)
And that is what you want. You want to compare arraysDocs here and do not change their type to string (which would have been the default if the parameter is not set).
array_unique does a strict comparison (=== in PHP), for arrays this means:
$a === $b TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
Output (Demo):
Array
(
[0] => Array
(
[a] => 1
[b] => Hello
)
[1] => Array
(
[a] => 1
[b] => other
)
)
First things first, you can not use plain array_unique for this problem because array_unique internally treats the array items as strings, which is why "Cannot convert Array to String" notices will appear when using array_unique for this.
So try this:
$result = array(
0=>array('a'=>1,'b'=>'Hello'),
1=>array('a'=>1,'b'=>'other'),
2=>array('a'=>1,'b'=>'other')
);
$unique = array_map("unserialize", array_unique(array_map("serialize", $result)));
print_r($unique);
Result:
Array
(
[0] => Array
(
[a] => 1
[b] => Hello
)
[1] => Array
(
[a] => 1
[b] => other
)
)
Serialization is very handy for such problems.
If you feel that's too much magic for you, check out this blog post
function array_multi_unique($multiArray){
$uniqueArray = array();
foreach($multiArray as $subArray){
if(!in_array($subArray, $uniqueArray)){
$uniqueArray[] = $subArray;
}
}
return $uniqueArray;
}
$unique = array_multi_unique($result);
print_r($unique);
Ironically, in_array is working for arrays, where array_unique does not.
If I assign values to array like this:
$foo[0] = 2;
$foo[1] = 3;
print_r($foo);
I get:
Array
(
[0] => 2
[1] => 3
)
But if I do:
$foo[1] = 3;
$foo[0] = 2 ;
print_r($foo);
I get:
Array
(
[1] => 3
[0] => 2
)
As you can see first goes array with index 1 and it confuses me, is it possible to make that it would start from 0
If you interested, I assign value to array with index 1 because I need to use that value for calculating array with index 0
try to use ksort();. It sorts your keys ascending
<?php
$foo[1] = 3;
$foo[0] = 2 ;
ksort($foo);
print_r($foo);
results in
Array (
[0] => 2
[1] => 3
)
demo
Try ksort()
The reason it is like this in PHP, is because arrays are a bit different from arrays in other languages. Arrays in PHP are somewhat similar to HashMaps in Java and Dictionaries in C#, although still a bit different.
You can also add
$foo[0] = '';
,before you add any value to $foo[1]