This question already has answers here:
Merge two flat indexed arrays of equal size so that values are pushed into the result in an alternating fashion
(2 answers)
Closed 6 years ago.
What I want is an efficient (without looping) way to merge arrays in the way that the first element of the resulting array is the first element of the first array, the second element of the resulting array is the second element of the second array (alternatively)... etc
Example:
$arr1 = array(1, 3, 5);
$arr2 = array(2, 4, 6);
$resultingArray = array(1, 2, 3, 4, 5, 6);
assuming both arrays have the same length.
$arr1 = array(1, 3, 5);
$arr2 = array(2, 4, 6);
$new = array();
for ($i=0; $i<count($arr1); $i++) {
$new[] = $arr1[$i];
$new[] = $arr2[$i];
}
var_dump($new);
Not that I'd really advocate this "hack", but this'll do:
$result = array();
array_map(function ($a, $b) use (&$result) { array_push($result, $a, $b); }, $arr1, $arr2);
It really just hides a double loop behind array_map, so, meh...
Related
This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 7 years ago.
I have one dynamic array, for example with following elements:
$myArray = array(1, 2, 3, 4, 5);
And I want my final array to be:
$finalArray = array(4, 1, 5, [whaterever]);
What's the best way to do custom sorting which is neither ascending or descending or doesn't follow any rule like this?
Thanks for your suggestions.
[Edit]
I have edited my question.
You can try the usort function. On the second argument, you should write a function that will decide how your array elements should be placed.
Something like this:
<?php
$myArray = [1, 2, 3, 4, 5];
$properOrder = [4, 1, 5, 2, 3];
usort($myArray, function($a, $b) use($properOrder) {
$index1 = array_search($a, $properOrder);
$index2 = array_search($b, $properOrder);
if ($index1 > $index2) {
return 1;
} else if ($index1 < $index2) {
return -1;
} else {
return 0;
}
});
print_r($myArray);
I want to merge 2 arrays together that have a different number of elements, using the keys from one and the values from another where/if the keys match. The array that contains the desired values may have less elements in it although I would like to retain the resulting empty keys from the original array. For example:
//Array that contains keys I would like to retain
$arr1 = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
//Array that contains values I'd like to use
$arr2 = array(01=>123, 03=>123, 05=>123, 07=>123, 09=>123, 11=>123);
//The desired result with some valueless elements
$results = array(01=>123, 02, 03=>123, 04, 05=>123, 06, 07=>123, 08, 09=>123, 10, 11=>123, 12);
As you can see the results array retains 12 elements but only applies values to where the keys from the 2 arrays match.
I have tried $results = array_intersect_key($arr1 + $arr2, $arr2); among other PHP functions as well as:
for ($i=1; $i < count($arr1); $i++) {
if (isset($arr2[$i])) {
$arr3[] = $arr2[$i];
} else {
$arr3[] = $arr1[$i];
}
}
print_r($arr3);
No luck as yet.
Thanks in advance!
For arrays like this
$arr1 = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
$arr2 = array(1=>123, 3=>123, 5=>123, 7=>123, 9=>123, 11=>123);
this should work.
foreach ($arr1 as $key) {
$results[$key] = isset($arr2[$key]) ? $arr2[$key] : null;
}
or using some other PHP functions:
$results = array_replace(array_fill_keys($arr1, null), $arr2);
//Array that contains keys I would like to retain
$arr1 = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
//Array that contains values I'd like to use
$arr2 = array(1=>123, 3=>123, 5=>123, 7=>123, 9=>123, 11=>123);
$result = array_fill_keys(
$arr1,
null
);
array_walk(
$result,
function(&$value, $key) use($arr2) {
$value = (isset($arr2[$key])) ? $arr2[$key] : null;
}
);
var_dump($result);
First set your $arr1's values to false to retain just the keys:
$arr1 = array_fill_keys(array_keys($arr1), false); Or if you're generating $arr1 yourself, define it as such to start with: $arr1 = Array(false, false, false, false /* etc. */);
Now use the array union operator:
$result = $arr2 + $arr1;
The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays — from the docs: http://php.net/manual/en/language.operators.array.php)
Then if required sort the array by key: ksort($array);
I have an array, and I want to find all of the indexes of a certain object in the array. When I use array_search, it only returns the first index in which the object can be found.
echo array_search(3, array(3, 3, 4));
This returns 0, but I want to know that both indexes 0 and 1 have the integer 3 as their object. Is there a way of doing this without using a for loop?
Try array_keys() method :
$array = array(3, 3, 4);
print_r(array_keys($array, "3"));
For reference:
array_keys() — Return all the keys or a subset of the keys of an array Info & usuage examples : http://php.net/manual/en/function.array-keys.php
As an alternative to array_keys, array_filter() retains associativity
$key = 3;
$array = array(1, 3, 3, 4, 3, 5);
$result = array_filter(
$array,
function ($item) use ($key) {
return ($item == $key);
}
);
var_dump($result);
What is the fastest way to convert a simple array to an associative array in PHP so that values can be checked in the isset($array[$value])?
I.e. fastest way to do the following conversion:
$array = array(1, 2, 3, 4, 5);
$assoc = array();
foreach ($array as $i => $value) {
$assoc[$value] = 1;
}
Your code is the exact equivalent of:
$assoc = array_fill_keys(array(1, 2, 3, 4, 5), 1); // or
$assoc = array_fill_keys(range(1, 5), 1);
array_flip(), while it may work for your purpose, it's not the same.
PHP ref: array_fill_keys(), array_flip()
If anyone is still wondering how to do this, there is an easier solution for this by using the array_combine function.
$array = array(1, 2, 3, 4, 5);
$assoc = array_combine($array,$array);
array_flip() is exactly doing that:
array_flip() returns an array in flip order, i.e. keys from trans become values and values from trans become keys.
Note that the values of trans need to be valid keys, i.e. they need to be either integer or string. A warning will be emitted if a value has the wrong type, and the key/value pair in question will not be flipped.
If a value has several occurrences, the latest key will be used as its values, and all others will be lost.
But apart from that, there is only one type of array in PHP. Even numerical ("simple", as you call it) arrays are associative.
Simply use this logic
$var1 = json_encode($arr1, JSON_FORCE_OBJECT);
$var1 = json_decode($var1);
where $arr1 is the array that has to be converted to associative array.
This can be achieved by json_encode and the json_decode the same
function simple_to_associative($array) {
$new_array = [];
$i = 0;
$last_elem = end($array);
$nr_elems = count($array);
foreach ($array as $index=>$value) {
if($i % 2 == 0 && $last_elem == $value) {
$new_array[$value] = '';
} elseif($i % 2 == 0) {
$new_array[$value] = $array[$index + 1];
}
$i++;
}
return $new_array;
}
Would work on any simple array of unlimited elements.
How to combine two arrays into single one and i am requesting this in such a way that the 3rd combination array should contains one value from one array and the next one from other array and so on.. or ( it could be random)
ex:
$arr1 = (1, 2, 3, 4, 5);
$arr2 = (10, 20, 30, 40, 50);
and combined array
$arr3 = (1, 10, 2, 20, 3, 30, ...);
If it can be random, this will solve your problem:
$merged = array_merge($arr1, $arr2);
shuffle($merged);
I also made a function for fun that will produce the exact output you had in your question. It will work regardless of the size of the two arrays.
function FosMerge($arr1, $arr2) {
$res=array();
$arr1=array_reverse($arr1);
$arr2=array_reverse($arr2);
foreach ($arr1 as $a1) {
if (count($arr1)==0) {
break;
}
array_push($res, array_pop($arr1));
if (count($arr2)!=0) {
array_push($res, array_pop($arr2));
}
}
return array_merge($res, $arr2);
}
This will return a random array:
$merged = array_merge($arr1,$arr2);
shuffle($merged);
sort($arr3 = array_merge($arr1, $arr2));
array_merge() will merge your arrays into one. sort() will sort the combined array.
If you want it random instead of sorted:
shuffle($arr3 = array_merge($arr1, $arr2));
$arr3 contains the array you're looking for.
You can use
<?php
arr3 = array_merge ($arr1 , $arr2 );
print_r(arr3);
?>
which will output in
$arr3 = (1,2,3,4,5,10,20,30,40,50)