Right now I feel like my head is going to explode trying to figure this out as I'm a beginner in PHP. I'm using wordpress and in my post I'm looping a series of custom fields which will output a number.
<?php echo get_post_meta ($card_id, 'card-cost', true); ?>
This will then output the numbers from the custom fields so for example lets say the post has 8 of these fields the numbers will show
2
2
3
4
2
5
5
3
What I need is to grab all the same numbers and add them together and set them to a variable
so for 2s we have 3 set so I I would assume something like this
$total2 = 2+2+2
$total3 = 3+3
$total4 = 4
$total5 = 5
The first thing I'm not sure about is how to execute the loop inside php so instead of printing the above numbers we can store them in php to than add them together.
Once we have them how do we have php pick out just the 2's to add together than just the 3s.
try this
<?php
$arr = array(2,4,2,5,8,9,8,9,8,8,8,9,4);
$aa = array_count_values($arr);
foreach($aa as $k=>$ar)
{
echo ($k * $ar) . '</br>';
}
?>
$myNumbers = [2, 2, 3, 4, 2, 5, 5, 3];
$results = [];
foreach ($myNumbers as $number){
$results[$number] = $results[$number] + $number;
}
// $results[2] will be the 2s, etc
print_r($results);
Related
I'm counting the number of elements in a section and it's an even number like 34, I would like to split them into three logical groups, like:
Group 1: 1 to 12 (12 items)
Group 2: 13-24 (12 items)
Group 3: 25-34 (10 items)
I want the PHP code to logically create three groups of items where the first two sets can hold equal number of items and the rest can go into the last set. There won't be more than three sets.
$whole_elements=33;
$group1 = ($whole_elements) / 3;
This kind of code would not work as it would return a value with decimal point.
You should divide your number by 3, round the result to obtain the first 2 numbers, then use a modulo to get the last one:
<?php
$whole_elements=34;
$group1 = $group2 = round($whole_elements / 3);
$group3 = $whole_elements % $group1;
?>
Then obtaining the "groups" is a matter of slicing the original array:
<?php
$group1_array = array_slice($original_array, 0, $group1);
$group2_array = array_slice($original_array, $group1, $group1);
$group3_array = array_slice($original_array, -$group3);
?>
In fact, using this method, you don't need to determine $group2 in the first bit of code as it's the same as $group1
$whole_elements = 34;
$third = ceil($whole_elements / 3);
$group1 = $group2 = $third;
$group3 = $whole_elements - 2*$third;
echo 'one: ' . $group1 . '<br/>two: ' . $group2 . '<br/>three: ' . $group3;
one: 12
two: 12
three: 10
I'm pretty new to PHP but I have built some fairly simple WordPress themes in my time. I'm trying to make something unique and I'm not sure how to accomplish it (or if it's even possible).
My goal is to create a loop that will dynamically close rows when it reaches the column "12" count for bootstrap (IE: col-md-3 + col-md-3 + col-md-6 = 12). The look I'm ultimately trying to achieve and how I currently have my static file set up => https://jsfiddle.net/y2mLr3hd/7/embedded/result/. I'm only using "display: flex;" for right now to just demonstrate what I'm trying to achieve. I'd like it be just rows rather than a single row.
I'm use to the standard loop for WordPress using ULs and LIs but I have no idea on how to go about what I'm trying to do. I'd like the loop to figure a random number for the column size consisting of the column sizes "3, 4, 6, 8" and create rows with columns sizes equaling "12" like I stated before. THAT or find a way on how to make it work with the way I currently have it set up.
This is the closest thing to what I'm looking for but really isn't even that close =>https://stackoverflow.com/questions/16427962/twitter-bootstrap-spans-in-dynamic-websites#=. Here's the code from that link for quick reference:
$i=0;
foreach ($posts as $post):
if ($i%2==0) echo '<div class="row-fluid">';
echo '<div class="span6">'. $post->content .'</div>';
if ($i%2==1) echo '</div>';
$i++;
endforeach;
Any help on how I might be able to go about this would be GREATLY appreciated!
There are two parts to your question:
How to divide 12 in random parts using 3, 4, 6, and 8
Given an array of numbers that add up to 12, how to generate a row with posts?
The first one is more a mathematics question. Note that you can only combine 3s and 6s, or 4s and 8s. You cannot combine 3 and 4, and still get 12.
We'll devise a simple algorithm with this in mind:
function getRandomNumbers()
{
// We start with an empty array and add numbers until we hit 12.
$result = array();
// We choose either 3 or 4 as basic number.
$x = mt_rand(3, 4);
// Now, as long as we don't hit 12, we iterate through a loop,
// adding either the basic number, or 2 times the basic number:
while (array_sum($result) < 12) {
// Randomly decide
if (mt_rand(0, 1) > 0) {
$newElement = 2 * $x; // This is either 6 or 8
// However, always make sure not to exceed 12:
if (array_sum($result) + $newElement > 12) {
$newElement = $x;
}
} else {
$newElement = $x; // This is either 3 or 4
}
// Add the new number to the array:
$result[] = $newElement;
}
// Return the resulting array
return $result;
}
Now we need to use these arrays to create rows. We start by generating an array with random numbers with the function we wrote.
We'll simply iterate through the posts, use the numbers in the array until there's none left. We'll generate a new array with random numbers whenever we need a new one. Since that means we have added 12 width-worth of columns, that's the point where we need to start a new row as well.
// Get the initial array with random numbers
$randomArray = getRandomNumbers();
// Open the initial row.
echo '<div>';
foreach ($posts as $post):
if (count($randomArray) < 1) {
// Close the row and start a new one:
echo '</div><div>';
// Get a fresh array with random numbers:
$randomArray = getRandomNumbers();
}
$nextRandomNumber = array_pop($randomArray); // This takes the next number.
echo '<div class="col-md-' . $nextRandomNumber . '">'. $post->content .'</div>';
endforeach;
echo '</div>'; // Close the final row.
i have this php code:
<?php
function GetRand($N, $min=1, $max=59) {
$Local = array();
mt_srand(time());
for ($i=0;$i<$N;$i++)
$LocalArr [] = mt_rand($min, $max);
return $LocalArr;
}
$A = GetRand(5);
foreach($A as $K=>$v) echo "$v ";
?>
The result is 5 numbers between 1 and 59. The problem is that sometimes i receive results like this:
43 9 13 9 7
In those 5 numbers, there is the number 9 twice. I would like to change the php code, so everytime when there is a number that repeats, this number should be skipped and instead of the repeated number should be represented another number, so that every time i have 5 numbers and no duplicates between them.
Thank you very much in Advance!
$numbers = range(1, 59);
shuffle($numbers);
var_dump(array_slice($numbers, 0, 5));
Try this (untested):
<?php
$randoms = array(rand(1,59));
while(sizeof($randoms) <= 5) {
$randoms[] = rand(1,59);
$randoms = array_unique($randoms);
}
what i want to do is something like memory game, but I keep cannot get the same number with the out put
$numbers = range(1, 15);
shuffle($numbers);
foreach($numbers as $key){
echo $numbers[array_rand($numbers)];
break;
}
now the out put will be something like this
4 2 3 3
1 5 3 6
2 3 4 5
10 9 8 10
but how to I do it as rand array and with same 2 array number, which is i can match the number.
what i want in out put is
2 3 1 4
3 4 2 1
5 6 9 7
7 9 6 5
so like this i can get the match in 2 same number
any idea how to do it?
thanks
Your question is a bit confusing and vague. I extrapolate that you want to shuffle and display an array of numbers, two of each, in random order. To do that:
<?php
$numbers = range(1, 5);
$numbers = array_merge($numbers, $numbers);
shuffle($numbers);
echo implode(' ', $numbers);
This outputs, for instance, 3 5 1 5 1 2 3 4 2 4.
The array_rand() call in the foreach in your code makes absolutely no sense. If the above isn't what you wanted, please revise your question to be clearer.
First you have to do an array with couple values
// Generate array with values from 1 to 8
$arNumbers = range(1, 8);
// Duplicate the array so get copy of each number
$arNumbers = array_merge($arNumbers, $arNumbers);
// Shuffle the array
shuffle($arNumbers);
// And now display them
foreach($arNumbers as $nNumber)
{
// Do some business
}
Hope it helps :)
Try this. It is a simple way.
$numbers=range(1, 15);
//Get 4 unique random keys from $numbers array.
$rand_keys = array_rand($numbers, 4);
//print out the random numbers using the
//random keys.
foreach ($rand_keys as $k=>$i) {
echo $numbers[$i]." ";
}
Hope this will helps you...
If I get you correctly, you can achieve what you want to do with the following:
// make sure these are even numbers
$rows = 4;
$cols = 4;
$set = range(1, ($rows * $cols) / 2);
$numbers = array_merge($set, $set);
shuffle($numbers);
foreach (array_chunk($numbers, $cols) as $row) {
foreach ($row as $col) {
printf('%-5d', $col);
}
echo "\n";
}
Outputs:
3 7 2 1
4 6 8 5
6 3 8 4
2 5 7 1
Do something like:
$numbers = range(1, 15);
shuffle($numbers);
$used_numbers = array();
foreach($numbers as $key){
$this_number = $numbers[array_rand($numbers)];
$used_numbers[] = $this_number;
echo $this_number;
break;
}
$_SESSION['numbers'] = $used_numbers;
Then you can use the $_SESSION to access the numbers on another page (after reload perhaps), or use the same $used_numbers array to access them.
If you try:
$numbers = range(1, 15);
shuffle($numbers);
$used_numbers = array();
foreach($numbers as $key){
$this_number = $numbers[array_rand($numbers)];
$used_numbers[] = $this_number;
echo $this_number;
break;
}
echo '<br />';
foreach($used_numbers AS $number) {
echo $number;
}
You will see it returns the same number.
I have created an array of data, from which I can loop through specific fields and echo these values out, but what I need to do is add these values to a new array, ultimately allowing me to find the average of the values in the new array. As i've said, I can echo out the data, and I think I've figured how to get the average, if only I can create the new array! Any help would be greatly appreciated as I just can't find the answer anywhere, and I'm running low on talent!
My table contains approx 25 fields, im pulling out a number of rows based on a session variable. In the instance im working on, I need to take just the values from 1 column in the table, and add these to an array. The code below will loop through the values, and echo them out, 1 at a time:-
while ($cdarray=mysql_fetch_array($calldata)) {
echo $cdarray['score_total'];
}
This gives me 25555 which are the 4 values I would expect 25, 5, 5, 5
I've tried
while ($cdarray=mysql_fetch_array($calldata)) {
$cdts = $cdarray['score_total'];
$cdtsar = array($cdts);
}
Which results in $cdts being assigned a value of 5,
Any help greatly appreciated!!
This will get your data from the array, place it into a new one and calculates the average.
$cdtsar = array();
while ($cdarray=mysql_fetch_array($calldata)) {
$cdtsar[] = $cdarray['score_total'];
}
$average = array_sum($cdtsar) / count($cdtsar);
It actually prints 25 and 5 and 5 and 5, but there are no spaces in between so it looks like "25555". To verify this yourself:
while ($cdarray=mysql_fetch_array($calldata)) {
echo $cdarray['score_total'];
echo " / ";
}
To get the average, you can either use
$sum = $count = 0;
$average = null;
while ($cdarray=mysql_fetch_array($calldata)) {
$sum += $cdarray['score_total'];
++$count;
}
// Make sure to guard against divide by zero
if ($count) {
$average = $sum / $count;
}
or you might have the database calculate the average for you, if changing the query is an option.
If you want to assign the elements to the new array use like this
$cdtsar = array();
while ($cdarray=mysql_fetch_array($calldata)) {
array_push($cdtsar,$cdarray['score_total']);
}
To find the average of the array
$sum = array_sum($cdtsar);
$num = sizeof($cdtsar);
$avg = $sum/$num;
echo $avg;