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 last year.
I'm trying to merge arrays but would like to alternate the order.
$combined = array_merge($vars,$mods);
gives me: one,two,three,1,2,3...
I'd like: one,1,two,2,three,3...
is there a way to do this?
You can use a for loop and refer to the index of each of the arrays you're combining.
$l = count($vars);
for ($i=0; $i < $l; $i++) {
$combined[] = $vars[$i];
$combined[] = $mods[$i];
}
In each iteration of the loop, you'll append one item from each of the original arrays. This will achieve the alternating effect.
As Steve pointed out, this can be done more simply using foreach:
foreach ($vars as $i => $value) {
$combined[] = $value;
$combined[] = $mods[$i];
}
Related
So I got two associative arrays containing key-value pairs. They share one key name, and I want to add one array to the other if the "name" values are equal.
So if you have these arrays:
$array1 = [name=>"Foo",
date=>array("2016-06-06", "2016-06-05", "2016-06-04"),
(some other key-value pairs)];
$array2 = [name=>"Foo",
date=>array("2016-06-06", "2016-06-05", "2016-06-04"),
download_count=>array(54,23,15),
(some other key-value pairs)];
the result should be something like this:
$newArray = [name=>"Foo",
date=>array("2016-06-06", "2016-06-05", "2016-06-04"),
(the other key-value pairs from $array1),
app=>array(
name=>"Foo",
date=>array("2016-06-06", "2016-06-05", "2016-06-04"),
download_count=>array(54,23,15),
(the other key-value pairs from $array2))]
Right now I try to loop through both of the array's to see where the names of both array's at index $i,$j are the same, and if they are combine the two.
Here is the code I use for that
foreach($array1 as $foo){
foreach($array2 as $bar){
if($foo["name"] == $bar["name"]){
$foo["app"] = $bar;
}
}
}
alternatively I tried with just regular for loops like this:
for($i = 0; $i < count($array1); $i++){
for($j = 0; $j < count($array2); $i++){
if($array1[$i]["name"] == $array2[$j]["name"]){
$array1[$i]["app"] = $array2[$j];
break;
}
}
}
The result from the first example is just $array1 (unchanged), and the result form the alternative example is an infinite loop.
Could someone help figure out how to get the desirable result?
Edit
Got it working, was just a beginners error in this case both for loops increased $i by one instead of the first loop adding one to $i and the other adding ine to $j
This is my Associative Array:
$vetor = array(
"Name"=> "myName",
"Tel"=> "555-2020",
"Age"=> "60",
"Gender"=> "Male"
);
How I can show only three elements using the loop for?
I tried this:
for($i=0; $i<=2; $i++){
echo $vetor[$i]."<br>";
}
But without success. How I can do this?
You referring to wrong indexes because to reference the first element on your array you have to do something like : $vetor["Name"] instead of $vetor[0]
$i = 0;
foreach($vetor as $key => $value){
if($i == 2){ break; }
echo $value;
$i++;
}
foreach makes more sense for an array like this, but if you want to use for for whatever reason, the problem you'll have is that the array doesn't have sequential numeric indexes that correspond to your loop increment variable. But there are other ways to iterate over the first three elements without knowing what the indexes are.
// this first step may not be necessary depending on what's happened to the the array so far
reset($vetor);
$times = min(3, count($vetor));
for ($i = 0; $i < $times; $i++) {
echo current($vetor).'<br>';
next($vetor);
}
If next moves the internal array pointer beyond the last array element, current($vetor) will return false, so setting $times using min with the number of times you want and the array count will prevent you from looping more times than there are items in the array.
Another way, if you don't care what the keys are, is to use array_values to convert the array keys to numbers.
$vetor = array_values($vetor);
for ($i=0; $i < 3; $i++) {
echo $vetor[$i].'<br>';
}
This question already has answers here:
Combining php arrays
(3 answers)
Closed 7 years ago.
I have two arrays:
$arr1= array("A","B","C");
$arr2= array("1","2","3");
Output i need as:
$arr3= array("A","1","B","2","C","3");
Can anyone help please?
If your first two arrays has the same length, you can use a loop to get the array you want:
<?PHP
$arr1= array("A","B","C");
$arr2= array("1","2","3");
$arr3=[];
for($i = 0; $i < count($arr1); $i++)
array_push($arr3, $arr1[$i], $arr2[$i]);
?>
It will return:
$arr3= array("A","1","B","2","C","3");
Take a look at array_merge()
array_merge ( array $array1 [, array $... ] )
Merges the elements of one or more arrays together so that the values
of one are appended to the end of the previous one. It returns the
resulting array.
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.
This will work to combine the two arrays together:
$output = $array1 + $array2;
This snippet could solve what you asked, also if arrays are not equal in length.
function array_interpolation($arr1, $arr2) {
$result = array();
$len1 = count($arr1);
$len2 = count($arr2);
$maxlen = max($len1, $len2);
for($i = 0; $i < $maxlen; $i++) {
if($i < $len1) {
array_push($result, $arr1[$i]);
}
if($i < $len2) {
array_push($result, $arr2[$i]);
}
}
return $result;
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Output array elements randomly with PHP
Lets say we have this code:
<? if (isset($specialoffers)) { ?>
<? foreach ($specialoffers as $value) { ?>
<div>product #</div>
<?};?>
<?};?>
For example this list may be different everytime, it may have 1 product, and it may have 58 products. I want do display only 10 products in the list and in a random order.
How to do that?
I would like not to touch the SQL query!
Take a look at the array_rand function which takes one or more random elements from an array.
So, you could do something along the lines of:
foreach (array_rand($specialoffers,10) as $key)
do_something_interesting_with $specialoffers[$key];
$specialoffers = array_splice( shuffle($specialoffers), 0, 9 );
Something like this might work.
You can use shuffle() to randomize the array.
http://php.net/manual/en/function.shuffle.php
You can do that with Reservoir Sampling which is even needed if the number of elements would exhaust your memory (and are presented through an iterator):
$randoms = new RandomIterator($specialoffers, 10);
foreach ($randoms as $value) {
...
}
You can find the source-code of the RandomIterator class as Gist.
Please try example for getting random value from assoc arrays;
function array_random_assoc( $arr, $num = 1) {
$keys = array_keys($arr);
shuffle($keys);
$r = array();
for ($i = 0; $i < $num; $i++) {
$r[$keys[$i]] = $arr[$keys[$i]];
}
return $r;
}
$specialoffers = (array_random_assoc($data_array, 10));
This question already has answers here:
How do I select 10 random things from a list in PHP?
(5 answers)
Closed 8 months ago.
From an array
$my_array = array('a','b','c','d','e');
I want to get two DIFFERENT random elements.
With the following code:
for ($i=0; $i<2; $i++) {
$random = array_rand($my_array); # one random array element number
$get_it = $my_array[$random]; # get the letter from the array
echo $get_it;
}
it is possible to get two times the same letter. I need to prevent this. I want to get always two different array elements. Can somebody tell me how to do that?
Thanks
array_rand() can take two parameters, the array and the number of (different) elements you want to pick.
mixed array_rand ( array $input [, int $num_req = 1 ] )
$my_array = array('a','b','c','d','e');
foreach( array_rand($my_array, 2) as $key ) {
echo $my_array[$key];
}
What about this?
$random = $my_array; // make a copy of the array
shuffle($random); // randomize the order
echo array_pop($random); // take the last element and remove it
echo array_pop($random); // s.a.
You could always remove the element that you selected the first time round, then you wouldn't pick it again. If you don't want to modify the array create a copy.
for ($i=0; $i<2; $i++) {
$random = array_rand($my_array); # one random array element number
$get_it = $my_array[$random]; # get the letter from the array
echo $get_it;
unset($my_array[$random]);
}
You can shuffle and then pick a slice of two. Use another variable if you want to keep the original array intact.
$your_array=[1,2,3,4,5,6,7];
shuffle($your_array); // randomize the order
$your_array = array_slice($your_array, 0, 2); //pick 2
foreach (array_intersect_key($arr, array_flip(array_rand($arr, 2))) as $k => $v) {
echo "$k:$v\n";
}
//or
list($a, $b) = array_values(array_intersect_key($arr, array_flip(array_rand($arr, 2))));
here's a simple function I use for pulling multiple random elements from an array.
function get_random_elements( $array, $limit=0 ){
shuffle($array);
if ( $limit > 0 ) {
$array = array_splice($array, 0, $limit);
}
return $array;
}
Here's how I did it. Hopefully this helps anyone confused.
$originalArray = array( 'first', 'second', 'third', 'fourth' );
$newArray= $originalArray;
shuffle( $newArray);
for ($i=0; $i<2; $i++) {
echo $newArray[$i];
}
Get the first random, then use a do..while loop to get the second:
$random1 = array_rand($my_array);
do {
$random2 = array_rand($my_array);
} while($random1 == $random2);
This will keep looping until random2 is not the same as random1