Populate new array in for loop from two other arrays - php

Hi I have been struggling with population of an array if you can help it will be much appreciated.
So I have these two arrays $start_range[] and $end_range[] which both contain
respective values and both arrays are of the same size. For example: $start_range[0] = 1000 and $end_range[0]=[2000]. Now I want to fill a new array with the range between those numbers and keep the respectiveness of the values so as in the example $new_array[0] = range($start_range[0],$end_range[0]).
In the moment I am using this code here
for ($i=0; $i<sizeof($start_range); $i++) {
$new_array[] = range($start_range[$i], $end_range[$i]);
}
But my problem is that it generates arrays with the same data because it loops through the size of the array. As if the size of the array was 4 then it will generate 4 new exact same arrays. I can't break out of the loop as it generates arrays only from the first columns of the two arrays.
Any solution?

Would this do?
$newArray = array();
foreach ($startArray as $key => $value) {
$newArray[$key] = range($startArray[$key], $endArray[$key]);
}

Related

Check difference between two array without any function

$array1=[1,2,3,4,5,6];
$array2=[1,2,3,5,6,7,8,9,10];
I want the difference between these two array without using any function like array_diff or etc
Obviously I'm not gonna answer this homework/interview task with a code dump, but with the general (and tedious) approach:
foreach over both lists ($array1 as $x1 / $array2 as $x2).
Keep a state flag $found = false;
If the inner foreach finds $x1 == $x2, then set $found
And after the inner loop, collect $x1 in a difference list (if (!$found)).
$diffArray=array();
foreach($array1 as $value){
if(!in_array($value,$array2)
$diffArray[$value] = $value;
}
foreach($array2 as $value){
if(!in_array($value,$array1)
$diffArray[$value] = $value;
}
Iterate over the arrays separately one by one, put the difference in array KEY as well to avoid repetition. In first loop, it will select the elements that are in array1 but not in array2 and in second loop it's vice versa.

Combine 2 arrays into 2d array without losing data

I have 2 arrays and want to combine into third array with one array as key and another as value. I tried to use array_combine(), but the function will eliminate all the repeated keys, so I want the result array as a 2d array. The sample array is as below:
$keys = {0,1,2,0,1,2,0,1,2};
$values = {a,b,c,d,e,f,g,h,i};
$result = array(
[0]=>array(0=>a,1=>b,2=>c),
[1]=>array(0=>d,1=>e,2=>f),
[2]=>array(0=>g,1=>h,2=>i)
);
//What i am using right now is:
$result = array_combine($keys,$values);
But it only returns array(0=>g,2=>h,3=>i). Any advice would be appreciated!
You can do it like below:-
<?php
$keys = array(0,1,2,0,1,2,0,1,2);
$values = array('a','b','c','d','e','f','g','h','i');
$values = array_chunk($values,count(array_unique($keys)));
foreach($values as &$value){
$value = array_combine(array_unique($keys),$value);
}
print_r($values);
https://eval.in/859753
Yes the above is working and i give upvote too for this but i dont know why you combine into the foreach loop its not necessary. The results are given in only in second line. Can you describe?
<?php
$keys = array(0,1,2,0,1,2,0,1,2);
$values = array('a','b','c','d','e','f','g','h','i');
$v = array_chunk($values,count(array_unique($keys)));
echo "<pre>";print_r($v);
?>
https://eval.in/859759
As a more flexible/robust solution, push key-value pairs into new rows whenever the key's value is already in the currently targeted row. In other words, there will never be an attempt to write a key into a row that already contains that particular key.
This can be expected to be highly efficient because there are no iterated function calls ...no function calls at all, really.
Code: (Demo)
$result = [];
foreach ($keys as $i => $key) {
$counter[$key] = ($counter[$key] ?? -1) + 1;
$result[$counter[$key]][$key] = $values[$i];
}
var_export($result);

randomly subtract desired percentage from a array using php

I have a array which contains 40 elements like this
$i = array('1','2','3','4','5','6','7','8','9','10','11',
'12','13','14','15','16','17','18','19','20','21','22','23','24',
'25','26','27','28','29','30','31','32','33','34','35',
'36','37','38','39','40');
now i have 4 variations like 5%, 10%, 15%, 20%
The requirement is i need to take array values randomly after subtracting the desired variation.
Lets say i used 5% variation so i need to separate 5% from the array ie 2 elements i need to remove randomly from the array and keep the rest 38 element in a new array randomly.so both the resulted array as well subtracted elements need to be in two different array.
I need a function with two parameter ie one is variation and another is required array ie resultant array or subtracted elements array.
This same sequence follows to all other variations.
Although I am not sure what you mean by rest 38 element in a new array randomly e.g. does this mean the new array is also shuffled? This is what I came up with.
<?php
function splitArray($variation, $array) {
$count = count($array); // Count the elements in the given array
$removeNumber = floor($count*($variation/100)); // Calculate the number of elements to remove
// Create an array holding the index numbers for splicing, these numbers are random.
for($i=0; $i<$removeNumber; $i++) {
$removeArray[] = rand(0,$count-1);
}
// Loop through the removeArray to retrieve the indexes to splice at.
for($i=0; $i<count($removeArray); $i++) {
$subArray[] = $array[$removeArray[$i]];
array_splice($array, $removeArray[$i], 1);
}
// return the newly spliced array and the spliced items array
return array($array, $subArray);
}
$oldArray = array('1','2','3','4','5','6','7','8','9','10','11',
'12','13','14','15','16','17','18','19','20','21','22','23','24',
'25','26','27','28','29','30','31','32','33','34','35',
'36','37','38','39','40');
$array = splitArray(5, $oldArray);
$subArray = $array[0];
$newArray = $array[1];
<?php
function subtractFromArray($array,$percentage){
//Randonmising the array
shuffle($array);
//percentage numeric equivalent wrt array aize
$substract_variation_count = floor(sizeof($array) * $percentage/100);
//New extracted array
$new_array = array_slice($array,$substract_variation_count);
//retuns the new array with 38 elements
return $new_array;
}
//array with all elements
$array = array('1','2','3','4','5','6','7','8','9','10','11',
'12','13','14','15','16','17','18','19','20','21','22','23','24',
'25','26','27','28','29','30','31','32','33','34','35',
'36','37','38','39','40');
//get new array
$new_array = subtractFromArray($array,5);
//print new array
print_r($new_array);
//Substracted array with 2 elements
$substrcated_array = array_diff($array,$new_array);
print_r($substrcated_array);
?>

PHP - Comparing an array with a multidimensional array?

I have two arrays, one of them is a one dimensional array, a product of an explode by \n and then exploded by comma on a csv file, the other array is a mysql_fetch_array that contains information from the database, my goal is to compare those arrays and find out the difference between them or new records that exist in the csv array and not in the database, i have tried array_diff, array_diff_assoc, array_udiff , i tried comparing each line of the csv file to the database using a select statement but its taking forever to load, i tried almost all the solutions here on stackoverflow.com, but i can't seem to compare those arrays.
This is a snippet from my code :
$input = file_get_contents('test.csv');
$newarray = explode("\n", $input);
$sql = mysql_query("SELECT * FROM products")or(die(mysql_error()));
$basearray = mysql_fetch_array($sql);
foreach ($newarray as $key => $value) {
$each_line = explode(",", $value);
// code goes here
// i tried producing a new array here and compare it
// to $basearray later, but it didn't work.
}

How should this array be looped? [duplicate]

This question already has answers here:
How to combine two arrays together?
(3 answers)
Closed 8 years ago.
To start off, let's look at the arrays -
$array1 = array('user#email.com','user2#email.com','user3#email.com'); // Imagine this has over a million users
$array2 = array('domain1.com','domain2.com'); // This may have between 10-20 domains
What I want to do is loop through the users and continuously assign a domain in the second array to a user in the first array. It should look like this when completed -
$finished = array('user#email.com' => 'domain1.com', 'user2#email.com' => 'domain2.com', 'user3#email.com' => 'domain1.com');
How can I loop through $array1 and sequentially assign a domain from $array2 to each user?
This is mind boggling me right now.
Just FYI array_combine() from the "Duplicate Answer" is incorrect to this answer. The correct answer is below. If $array1 has 5,000,000 emails in it and $array2 has 10 domains in it, the finished array would only give the first 10 items in the array a corresponding domain. Those who marked it duplicate did not read the full description, or do not understand PHP.
Similar to Barmar's, but using the key:
$count = count($array2);
foreach($array1 as $key => $value) {
$finished[$value] = $array2[$key % $count];
}
This works with your posted arrays, however if you have lets say all even or all odd keys in $array1 this would bomb, also with an associative array.
Increment an index in $array2 modulo its size as you assign values.
$index = 0;
$finished = array();
foreach ($array1 as $email) {
$finished[$email] = $array2[$index];
$index = ($index + 1) % count($array2);
}
Make a loop over the larger set. Keep a secondary index variable, and each iteration, increment it, then set it to its value modulo the size of the smaller set. Use this secondary index as the index into your second set to assign to the element from the first set.

Categories