PHP: Loop through a multidimesional PHP array - php

I've got an array of 'contestant entrants' which can be shown like this:
$all_entrants = array(
array('username'=>'122', 'number_of_entries'=>1),
array('username'=>'123', 'number_of_entries'=>4),
array('username'=>'124', 'number_of_entries'=>3),
...
)
From these entries I need to create another array called $draw.
The $draw array will have username repeated as many times as it's corresponding number_of_entries. So for the above example it might look like this:
$draw = array("122", "123", "123", "123", "123", "124", "124", "124")
I want this so that I can later generate a random number, and find the winner by doing something like $draw[$randomNumber];
However I cannot get my head around how to create that $draw array from the $all_entrants array... Any help will be greatly appreciated!

I assume you're looking for something like this?
$draw = array();
foreach($all_entrants as $entrant) // loop through array with entrants
for ($i = 0; $i<$entrant['number_of_entries']; $i++) //get number of entries
$draw[] = $entrant['username']; //add them to the $draw array

I think it's a question about select one from a group of name which has different weight.
maybe an array like this
$group = array(
array('122' => 1),
array('123'=> 4),
array('124'=> 3)
);
First Calculate the sum of the weight, or may be it has been known already
$total_weight = 0;
foreach($group as $weight){
$total_weight += $weight;
}
Then generate a random number from 0 to $total_weight, eg. 0<=$rand_number
$current_total = 0;
foreach($group as $name => $weight){
if($rand_number <= $current_total)
return $name;
$current_total += $weight;
}
--
BTW, I'm new here, more to learn:)

<?php
$draw = array();
foreach($all_entrants as $entrant) {
for($i=0; $i<$entrant['number_of_entries']; $i++) {
$draw[] = $entrant['username'];
}
}

$draw = array();
foreach($all_entrants as $entrant) {
for($i=0; $i<$entrant['number_of_entries']; $i++) {
$draw[] = $entrant['username'];
}
}

$all_entrants = array(
array('username'=>'122', 'number_of_entries'=>1),
array('username'=>'123', 'number_of_entries'=>4),
array('username'=>'124', 'number_of_entries'=>3),
);
$draw = array();
foreach($all_entrants as $entrant) {
$draw = array_merge(
$draw,
array_fill(0, $entrant['number_of_entries'], $entrant['username'])
);
}
var_dump($draw);

Try this
$newarray=array();
foreach($all_entrants as $list){
for($i=1;$i<=$list['number_of_entries'];$i++){
array_push($newarray,$list['username']);
}
}

<?php
$all_entrants = array(
array('username'=>'122', 'number_of_entries'=>1),
array('username'=>'123', 'number_of_entries'=>4),
array('username'=>'124', 'number_of_entries'=>3)
);
$draw = array();
for ($i = 0; $i < count($all_entrants); $i++)
{
$entrants = $all_entrants[$i];
$name = $entrants["username"];
$entry_count = $entrants["number_of_entries"];
for ($j = 0; $j < $entry_count; $j++) $draw[] = $name;
}
print_r($draw);
?>
Hope it helps.

check this :--
$result=array();
$all_entrants = array(
array('username'=>'122', 'number_of_entries'=>1),
array('username'=>'123', 'number_of_entries'=>4),
array('username'=>'124', 'number_of_entries'=>3)
);
foreach($all_entrants as $value)
for($i=0;$i<$value['number_of_entries'];$i++)
array_push($result,$value['username']);
echo '<pre>';
print_r($result);
output :-
Array
(
[0] => 122
[1] => 123
[2] => 123
[3] => 123
[4] => 123
[5] => 124
[6] => 124
[7] => 124
)

Related

How do I loop two array as one in PHP

I have a probrem but I don't know how to fix it,
here is two array
first is$X = A,B,C,D
second likes this a[1]a[2]a[3]a[4]a[5]a[6]a[7]a[8]
I want to loop likes this
Aa[1]a[2]
Ba[3]a[4]
Ca[5]a[6]
Da[7]a[8]
now i write likes this
foreach($X as $key) {
for ($i = 0; $i < 8; $i++) {
$a[$i];
}
$g=$a[$key][$i];
}
But it isn't that thing I want.
how can I fix it? thank you for your help.
You can try for
<?php
$X = ['A','B','C','D'];
$Y = ['a[1]a[2]','a[3]a[4]','a[5]a[6]','a[7]a[8]'];
$result = [];
for ($i=0; $i < sizeof($X) ; $i++) {
$result[] = $X[$i].$Y[$i];
}
?>
Output
Array
(
[0] => Aa[1]a[2]
[1] => Ba[3]a[4]
[2] => Ca[5]a[6]
[3] => Da[7]a[8]
)

How to create dummy values with keys + array php

how to create dummy data based on what we give number like this format
for example when i give $var=2, so it will create two, when i give $var=100, it will create 100 like this using arrays in php
create like this based on number given, give 2 create like this
[{"email":"test#test.com"},{"email":"test#test.com"}]
give 4 create like this
[{"email":"test#test.com"},{"email":"test#test.com"},{"email":"test#test.com"},{"email":"test#test.com"}]
Use array_fill:
$emails = array_fill(0, 100, 'test#test.com');
With your structure it is:
$emails = array_fill(0, 100, ['email' => 'test#test.com']);
You could do this:
<?php
$dummy = array();
$dummyAmount = 100;
for($i = 0; $i < $dummyAmount; $i++){
$dummy[] = array("email" => "test#test.com");
}
?>
Try this:
$a = [];
$var = 100;
for( $i = 0; $i < $var; ++$i ) {
$a[] = [
'email' => 'test#test.com'
];
}
$json = json_encode($a)
Well, use a loop with as many circles as you need.
And inside the loop, create your email addresses.
Like a so:
$amount = 100;
$emails = [];
for ($i = 0; $i < $amount; $i++) {
$emails[] = ['email' => 'test#test.com' ];
}
And then json encode it to get your expected output:
$emailJSON = json_encode($emails);

create array with key and value from string

I have a string:
$content = "test,something,other,things,data,example";
I want to create an array where the first item is the key and the second one the value.
It should look like this:
Array
(
[test] => something
[other] => things
[data] => example
)
How can I do that? It's difficult to search for a solution because I don't know how to search this.
It's very similar to this: Explode string into array with key and value
But I don't have a json array.
I tried something like that:
$content = "test,something,other,things,data,example";
$arr = explode(',', $content);
$counter = 1;
$result = array();
foreach($arr as $item) {
if($counter % 2 == 0) {
$result[$temp] = $item;
unset($temp);
$counter++;
} else {
$temp = $item;
$counter++;
continue;
}
}
print_r($result);
But it's a dirty solution. Is there any better way?
Try this:
$array = explode(',',$content);
$size = count($array);
for($i=0; $i<$size; $i++)
$result[$array[$i]] = $array[++$i];
Try this:
$content = "test,something,other,things,data,example";
$data = explode(",", $content);// Split the string into an array
$result = Array();
$size = count($data); // Calculate the size once for later use
if($size%2 == 0)// check if we have even number of items(we have pairs)
for($i = 0; $i<$size;$i=$i+2){// Use calculated size here, because value is evaluated on every iteration
$result[$data[$i]] = $data[$i+1];
}
var_dump($result);
Try this
$content = "test,something,other,things,data,example";
$firstArray = explode(',',$content);
print_r($firstArray);
$final = array();
for($i=0; $i<count($firstArray); $i++)
{
if($i % 2 == 0)
{
$final[$firstArray[$i]] = $firstArray[$i+1];
}
}
print_r($final);
$content = "test,something,other,things,data,example";
$x = explode(',', $content);
$z = array();
for ($i=0 ; $i<count($x); $i+=2){
$res[$x[$i]] = $x[$i+1];
$z=array_merge($z,$res);
}
print_r($z);
I have tried this example this is working file.
Code:-
<?php
$string = "test,something|other,things|data,example";
$finalArray = array();
$asArr = explode( '|', $string );
foreach( $asArr as $val ){
$tmp = explode( ',', $val );
$finalArray[ $tmp[0] ] = $tmp[1];
}
echo "After Sorting".'<pre>';
print_r( $finalArray );
echo '</pre>';
?>
Output:-
Array
(
[test] => something
[other] => things
[data] => example
)
For your reference check this Click Here
Hope this helps.
You could able to use the following:
$key_pair = array();
$arr = explode(',', $content);
$arr_length = count($arr);
if($arr_length%2 == 0)
{
for($i = 0; $i < $arr_length; $i = $i+2)
{
$key_pair[$arr[$i]] = $arr[$i+1];
}
}
print_r($key_pair);
$content = "test,something,other,things,data,example";
$contentArray = explode(',',$content);
for($i=0; $i<count($contentArray); $i++){
$contentResult[$contentArray[$i]] = $contentArray[++$i];
}
print_r( $contentResult);
Output
Array
(
[test] => something
[other] => things
[data] => example
)
$contentResult[$contentArray[1]] = $contentArray[2];
$contentResult[$contentArray[3]] = $contentArray[4];
$contentResult[$contentArray[5]] = $contentArray[6];

PHP Pick random array values based on total

I have array in php like
$randomarray = array('1106'=>'5','1110'=>'2','11867'=>'3','1206'=>'2','1210'=>'1','1223'=>'6','1235'=>'3','12565'=>'4','1258'=>'5','12690'=>'2','12693'=>'3','1283'=>'1','12944'=>'5');
I want to randomly pick elements from the array with the count of exactly 20. Each element have to only one time
I tried some array random example. I can't able to get the exact total which i expect.
this is the example of what i did that. But loop went to infinitive,
function randomTo($numIn) {
global $randomarray;
$numOut = 0;
$numbers = array();
do {
$key = array_rand($randomarray );
$add = $mainarray[$key];
if($numOut + $add > $numIn)
continue;
$numOut += $add;
$numbers[] = $add;
unset($mainarray[$key]);
} while( $numOut != $numIn );
return $numbers;
}
$testdata = randomTo(20);
The problem that you're trying to solve is called Subset sum and it's a subset of the Knapsack problem.
Just google for it, and while you're at it, google for Dynamic programming as it's a way of approaching the problem.
if(count($randomarray)) > 20
print_r(array_rand($randomarray, 20));
Get some Idea from this :
An example for getting random value from arrays
$r = array();
for ($i = 0; $i < $num; $i++) {
$r[] = $arr[$i];
}
return $num == 1 ? $r[0] : $r;
}
$a = array("apple", "banana", "cherry");
print_r(array_random($a));
print_r(array_random($a, 2));
?>
cherry
Array
(
[0] => banana
[1] => apple
)
And example for getting random value from assoc arrays;
<?php
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;
}
$a = array("a" => "apple", "b" => "banana", "c" => "cherry");
print_r(array_random_assoc($a));
print_r(array_random_assoc($a, 2));
?>
Array
(
[c] => cherry
)
Array
(
[a] => apple
[b] => banana
)

PHP Array explode single value

I have an array with a single value collected from database.
Within a while loop I wish to explode this for every two values.
Example:
$data = array('20;40;60;80;100;150;200;300;500;1000');
I want to explode this value and end up with the following loop:
$lowprice = "20";
$highprice = "40";
I couldn't find any examples of this.
Many thanks everyone who answered!
You can use preg_match_all().
Example:
$text = '20;40;60;80;100;150;200;300;500;1000';
preg_match_all("/([^;]+);([^;]+)/", $text, $pairs, PREG_SET_ORDER);
foreach ($pairs as $pair) {
// ...
$lowvalue = $pair[1];
$highvalue = $pair[2];
// ...
}
If you really must use explode and a while loop, the following will also work:
$text = '20;40;60;80;100;150;200;300;500;1000';
$data = explode(';', $text);
$i = 0;
$count = count($data);
while ($i < $count) {
// ...
$lowvalue = $data[$i++];
$highvalue = $data[$i++];
// ...
}
If you just want the first and second values as your low/high:
$data = array('20;40;60;80;100;150;200;300;500;1000');
list($lowprice,$highprice) = explode(';',current($data));
echo '$lowprice=',$lowprice,PHP_EOL;
echo '$highprice=',$highprice,PHP_EOL;
If you want an array of lows and highs:
$data = array('20;40;60;80;100;150;200;300;500;1000');
$lowprices = $highprices = array();
$data = explode(';',current($data));
$dataCount = count($data);
var_dump($data);
for ($i=0; $i < $dataCount; $i += 2) {
$lowprices[] = $data[$i];
$highprices[] = $data[$i+1];
}
echo '$lowprices=';
var_dump($lowprices);
echo '$highprices=';
var_dump($highprices);
EDIT
Why not start out with a proper array of values in the first place: it would simplify this a lot
$data = array(20,40,60,80,100,150,200,300,500,1000);
list($lowprice,$highprice) = $data;
echo '$lowprice=',$lowprice,PHP_EOL;
echo '$highprice=',$highprice,PHP_EOL;
or
$data = array(20,40,60,80,100,150,200,300,500,1000);
$lowprices = $highprices = array();
$dataCount = count($data);
var_dump($data);
for ($i=0; $i < $dataCount; $i += 2) {
$lowprices[] = $data[$i];
$highprices[] = $data[$i+1];
}
echo '$lowprices=';
var_dump($lowprices);
echo '$highprices=';
var_dump($highprices);
Explode initially on the ;. Then in a for loop incrementing by 2, you can assign the current and next values to a sub-array:
$initarray = explode(";", "20;40;60;80;100;150;200;300;500;1000");
$num = count($initarray);
// Main array to hold subarrays
$outputarray = array();
for ($i=0; $i<$num; $i=$i+2) {
// Add the current pair ($i and $i+1) to a sub-array
$outputarray[] = array("lowprice"=>$initarray[$i], "highprice"=>$initarray[$i+1]);
}
Outputs:
Array
(
[0] => Array
(
[lowprice] => 20
[highprice] => 40
)
[1] => Array
(
[lowprice] => 60
[highprice] => 80
)
[2] => Array
(
[lowprice] => 100
[highprice] => 150
)
[3] => Array
(
[lowprice] => 200
[highprice] => 300
)
[4] => Array
(
[lowprice] => 500
[highprice] => 1000
)
)
You may use loop like this one (using explode() and array_shift()):
$data = explode( ';', '20;40;60;80;100;150;200;300;500;1000');
while( count( $data) > 1){
$lowprice = array_shift( $data);
$highprice = array_shift( $data);
}
Or use for loop (should be more effective than calling count() in every iteration):
$count = count( $data);
for( $i = 0; $i < $count; $i+=2){}

Categories