BACKGROUND: I have a database that looks like this.
TITLE ANDROID OS X WINDOWS
World of Goo 1 1 1
Superman 64 GOTY Edition 0 1 1
Seinfeld: The Game 1 0 1
And so on, intended to represent a game collection. There's one varchar column representing the title, and then booleans for each platform.
My desire is to use PHP to turn that database into a page that reads
Super Mario 64 (N64)
World of Goo (Windows, Android)
And so on, just listing off which platforms a title is available for.
PROBLEM: Depending on which solution I use, I either wind up with (Windows) (Android) or (Windows,Android)(Windows,Android)(Windows,Android)(Windows,Android).
Here's what's written.
$q = mysqli_query($c,"SELECT * FROM GAMES");
while ($row = mysqli_fetch_assoc($q)) {
$platforms = array();
foreach ($row AS $column => $value) {
if ($column == "Name") {
echo "<br />" . $value;
continue;
}
if ($value == 1) {
array_push($platforms,$column);
}
if (count($platforms)) {
print_r($platforms);
}
}
}
The intent of this code is
Loop over every item in a row.
If the cell you're on is the name, echo it.
If the cell you're on has a "1" in it, then we own the game for that platform, so store the name of that platform in an array.
At the end of the row, show me that array.
Now here's the problem: if I execute that code, the array is fully-formed, but I don't get one array back, I get one array per column in my database, so it just echoes the platforms back over and over.
If I move line #3 ("$platforms = array();") into the foreach loop, then that problem is avoided, but I don't get one fully-formed array, I get a separate array for each individual platform.
So... where should I be putting that line? I'm messing something simple up with the way I manage that platforms array, but I'm not clever or experienced enough to figure it out. Any help would be fantastic.
This should resolve your issue.
while ($row = mysqli_fetch_assoc($q)) {
$platforms = array();
echo $row['TITLE'];
foreach($row as $column => $val):
$val == 1 ? $platforms[] = $column:;
endforeach;
echo '<pre>', print_r($platforms, true) ,'</pre>';
}
Related
I can't think my way through this one. I'm still learning arrays so go easy on me. I'm using codeigniter.
I have 3 tabs (1 month, 2 month, 3 month) in my mark-up.
Each tab shows 3 price boxes (3 levels - basic=1, standard=2, featured=3).
I need to display 9 prices overall, pulled from 1 look-up:
return $this->db->get('prices')->result_array();
In the database it's like this
Should I be trying to do it from one look-up as shown in my model or should I be doing several look-ups, or should I just be managing that look-up in the controller setting vars, ready to display in the view or just doing everything in the view? And How? The only think of 3x foreach loops, where inside the loop I say:
if($prices['months']==3) echo $prices['level'].' is '.$prices['amount'].'<br>';
I'd like to know the BEST way to do this but also how to do the array from one look-up, because I think I really need to get my head around arrays properly. Thanks :)
-- EDIT to show what I've ended up using below --
In the controller, sort of inspired by array_chunk but more manual and to allow for the table to expand, is setting array keys which I read up on in php manual:
foreach ($prices as $price_row) {
$data['prices'][$price_row['months']][] = $price_row;
}
Then in the view I can just use foreach for a month:
foreach ($prices[1] as $p) {
echo level_name($p['level']).' = '.$p['amount'].'<br>';
}
i did not test this so might have made a stupid error - but basically you can foreach through each of your products - make an array - and then use that array in your view.
// in your model Note I am returning an object not an array
// and always check to make sure something got returned
if( ! $products = $this->db->get('prices')->result() )
{
return false:
}
else
{
$prices = array();
foreach($products as $product)
{
// append the months number to the word 'months' to make it clear
$month = $product->months . 'month' ;
// same with level
$level = 'level' . $product->level ;
// build the array
$prices[$month][$level] = $product->amount ;
}//foreach
return $prices ;
}//else
so then in your controller - make sure something came back from the model, assign it to data, then pass data to your view
if( ! $data['prices'] = $this->somemodelname->returnPrices() )
{
$this->showError() ;
}
else
{
$this->load->view('yourviewname', $data);
}
and then in your view you could foreach or just echo out each price if it needs to follow some layout.
echo '1 month level 1 $' . $prices['1month']['level1'] ;
and remember your best friend when doing arrays is print_r wrapped in pre tags so like
echo 'start prices <br> <pre>' ;
print_r($prices) ;
echo '</pre>' ;
opinions - its fine to build stuff in the controller and the view while you are developing and building out. but get in the habit of refactoring to your models. keep your controllers as clean and thin as possible. if your views need complicated data structures - build them in a model first. that way if something goes wrong - your controller can decide what to do. AND you don't have to check in your view if $prices is set and valid because you have already done it. this minimizes where things can go wrong.
Here's a pretty easy way to sort the db return into separate arrays and then display them. #caralot stole my thunder so I came up with this alternative.
Using your current model return $this->db->get('prices')->result_array(); and assigning it to $data.
$data = $this->db->functionName();
//You should check $data validity but I'm skipping that
$month1 = [];
$month2 = [];
$month3 = [];
foreach($data as $row)
{
if($row['months'] === '1')
{
$month1[] = $row;
}
elseif($row['months'] === '2')
{
$month2[] = $row;
}
else
{
$month3[] = $row;
}
}
echo "Month 1<br>";
foreach($month1 as $month){
echo "Level ". $month['level'].' is '.$month['amount'].'<br>';
}
echo "Month 2<br>";
foreach($month2 as $month){
echo "Level ".$month['level'].' is '.$month['amount'].'<br>';
}
echo "Month 3<br>";
foreach($month3 as $month){
echo "Level ".$month['level'].' is '.$month['amount'].'<br>';
}
If your table was less ordered than what you show it would be necessary to add a $this->db->order_by('level', 'ASC'); call to the query.
It is such a tiny dataset that you should definitely do a single lookup. Sorting the array into three arrays in your controller would make more sense as it will leave your view much cleaner, and allow you to set defaults should there be no data (say level 1 for 3 months is removed) if you need to. You are always going to need three foreach loops unless you construct the entire table in one go, setting breaks and new column headings when the level indicator changes.
There is no 'Best' way to do this, it is all case dependent on complexity of layout, future data development and your requirements. Usually though you minimize the number of queries, and keep data manipulation to a minimum within you views. So ideally you will have three arrays, one for each column, sent to your view.
In your controller,
$result = $this->db->query("SELECT * from prices");
$result=$result->result();
$tab1=array();
$tab2=array();
$tab3=array();
foreach ($result as $res) {
switch($res->months)
{
case 1: array_push($tab1, $res);
break;
case 2: array_push($tab2, $res);
break;
case 3: array_push($tab3, $res);
break;
}
}
//var_dump($tab3); //array tab1 for month1, array tab2 for month2, array tab3 for month3
$data['tab1']=$tab1;
$data['tab2']=$tab2;
$data['tab3']=$tab3;
$data['include']=$this->load->view('myview', $data);
In your view i.e myview in my case,
<?php
if(!empty($tab1))
{
echo "Tab 1"."<br>";
foreach($tab1 as $tb)
{
echo "For level ".$tb->level." price is ".$tb->amount."<br>";
}
}
if(!empty($tab2))
{
echo "Tab 2"."<br>";
foreach($tab2 as $tb)
{
echo "For level ".$tb->level." price is ".$tb->amount."<br>";
}
}
if(!empty($tab3))
{
echo "Tab 3"."<br>";
foreach($tab3 as $tb)
{
echo "For level ".$tb->level." price is ".$tb->amount."<br>";
}
}
?>
I have two arrays. One array $People currently creates number of 44 individuals. Lets just assume currently its
$People = array('1','2',...,'44');.
I have another array of 15 elements.
$Test = array('A','B',...'O');
Now I want to be able to assign the test randomly to each individual. I know how to do this using random function in php.
Where it has got tricky for me and what I need help with is how can I even out the test array. What I mean by this is since there are currently 44 individuals (this array will grow in future), what I want is 14 test versions to have 3 individuals and 1 version would have 2. So I want the test array to even out. I also want it to handle as growth of $People array.
Ex: Test Version D will have individual '4', '25'. Every other version has three random individuals.
Few ideas I came up with are things like running random integer on $Test array and which ever gets highest/lowest gets 2 individuals and rest three. This would give a problem when I increase the size of $People array; to deal with that I though about using modulus to figure out what will be even number of $Test beforehand.
I can do this and other ideas but am pretty sure there has to be a better way to do this.
Clarifying your situation:
You want to distribute the values inside $People randomly amongst your $Test array. The problem you stated you are having is that the amount of values in $People isn't always perfectly dividable by the amount of values in $Test, and you aren't sure how to go about implementing code to distribute the values evenly.
Proposed solution:
You could obtain the values in a foreach loop randomly 1 by 1 from a shuffled version of $People and put them in a new array called $Result. You would also have a conditional checking if you have extracted all the values from the shuffled $People array: if($count>=$arrayCount) where $arrayCount=$count($shuffledPeople);. If you have obtained all the values, you first make the $bool value false (in order not to iterate through the while loop anymore, and then you break; out of the foreach loop.
$Result =[];//the array containing the results
$shuffledPeople = $People;
shuffle($shuffledPeople);//mixing up the array
$arrayCount = count($shuffledPeople);//finding the total amount of people
$count = 0;
$bool = TRUE;
while ($bool)
{
foreach($Test as $value)
{
$Result[$value][] = $shuffledPeople[$count];
$count++;
if ($count>=$arrayCount)
{
$bool = FALSE;
break;
}
}
}
To view the results, all you would need to do is:
foreach ($Result as $key => $value)
{
echo "{$key}: <br>";
if (is_array($value))
{
foreach ($value as $something)
{
echo "-->{$something}<br>";
}
}
else
{
echo "-->{$value}<br>";
}
}
I believe that this is what you want to do...
Assume that you have $people and $test arrays. You want to know how many people per test...
$ppt = ceil(sizeof($people)/sizeof($test));
Now, $ppt is the people per test. The next step is to shuffle up the people so they are randomly assigned to the tests.
shuffle($people);
Now, we can chunk up the people into sub-arrays such that each sub-array is assigned to a test. Remember, the chunks are random now because we shuffled.
$chunks = array_chunk($people, $ppt);
Now, everyone in $chunks[0] will take $test[0]. Everyone in $chunks[1] will take $test[1]. Everyone in $chunks[2] will take $test[2].
In essence, I have 3 arrays. These are serialised, stored to the DB, un-serialised and then outputted to a page. myFirstArray, mySecondArray, & myThirdArray.
From what I gather - I need to be using a foreach loop, or a for loop with a counter, as the 3 arrays are all of (the same) unknown length. By that I mean one user may have stored 4 items into each of the 3 arrays, but another user might have stored 8 items into each of the 3 arrays.
I'm trying to get the output to look something like this:
myFirstArray[0], mySecondArray[0], myThirdArray[0]
myFirstArray[1], mySecondArray[1], myThirdArray[1]
myFirstArray[2], mySecondArray[2], myThirdArray[2]
The current code I have is as follows:
foreach ($myFirstArray as $value1){
echo $value1 . " ";
}
foreach ($mySecondArray as $value2){
echo $value2 . " ";
}
foreach ($myThirdArray as $value3){
echo $value3 . "<br>";
}
I am aware that this code is never going to output my arrays as I would like, but I'm having some difficulty with working out the logic behind what I need. I haven't rushed straight to StackOverflow to ask, but nothing else I've seen has been very helpful!
Since both arrays have the same length, I propose
$length = count($myFirstArray);
for($i = 0; $i <$length ; $i++) {
echo $myFirstArray[$i].','.$mySecondArray[$i].','.$myThirdArray[$i].'<br/>';
}
This will loop through all of your arrays at the same time :) .
This is a brilliant little trick if I can get it to work - I have hundreds data columns from dozens of tables spread across a dozen data forms (they are HTML print forms) and they are all html with embedded php variables. Very normal. However the customer had a requirement to know what field went in where - a very good question.
So what did I do? I worked on a solution that allows the key'd arrays from the database to give up their column names. a brilliant move! except I need to do it via variable variables, and guess what, they DON'T work in a foreach loop.
here is the code
if ($_REQUEST['data']=="false"){
$supera = array("RowService", "RowSite", "RowCustomer", "RowEngineer"); //there can be many of these they are key'd arrays $RowService['column_name_1']; is the format
foreach($supera as $super){
foreach(${$super} as $key=>$value){
if (!is_numeric($key)){
${$super}[$key] = "<span style=\"color:pink;\">".$key."</span>";
}
}
}
}
as you can see I want a kill switch easy mechanism to cut and paste the key'd arrays that aren't to show real data any more rather they are to show (in pink) the column name, and (perhaps) the table name too. There is a lot of code already in place and this would be a brilliant option if it can be made to work
EDIT: this is the PHP error:
Warning: Invalid argument supplied for foreach()
EDIT: THE CODE ACTUALLY ALREADY WORKS: FIX IS TO test for is_array()
if(is_array(${$super})) foreach(${$super} as $key=>$value){
will work, as opposed to just
foreach(${$super} as $key=>$value){
I'm not sure what you are trying to achieve but your code (simplified) works just fine:
$a = array("asd", "qwe");
$asd = array("a" => 1, "b" => 2, "c" => 3);
$qwe = array("d" => 4, "e" => 5, "f" => 6);
foreach ($a as $item)
{
foreach ($$item as $key => $value)
{
echo $key . ": " . $value . "<br />";
}
}
Output:
a: 1
b: 2
c: 3
d: 4
e: 5
f: 6
Most likely one of your variables is empty (not an array) and that's why you receive that warning.
Personally, I find variable variables to be a really bad idea. There are a few ways around it.
For example:
$process = array(&$RowService,&$RowSite,&$RowCustomer,&$RowEngineer);
foreach($process as $p) {
foreach($p as $k=>$v) {
$p[$k] = "<span style=\"color:pink\">".$v."</span>";
}
}
Using references means you can affect the original variables.
If the above doesn't work (I'm not that great with references XD), try this:
$process = array($RowService,$RowSite,$RowCustomer,$RowEngineer);
foreach($process as $p) {
foreach($p as $k=>$v) {
$p[$k] = "<span style=\"color:pink\">".$v."</span>";
}
}
list($RowService,$RowSite,$RowCustomer,$RowEngineer) = $process;
As per my understanding of your requirement.
If you want to get table name with pink color then you just need to use below code
$supera = array("RowService", "RowSite", "RowCustomer", "RowEngineer"); //there can be many of these they are key'd arrays $RowService['column_name_1']; is the format
$super = array();
foreach($supera as $key=>$value){
if (!is_numeric($value)){
$super[$value] = "<span style=\"color:pink;\">".$value."</span>";
}
}
print_r($super);
The code below is written mainly using PHP, but I am hoping to speed up the process, and parsing strings in PHP is slow.
Assume the following where I get a string from the database, and converted it into an array.
$data['options_list'] = array(
"Colours" => array('red','blue','green','purple'),
"Length" => array('3','4','5','6'),
"Voltage" => array('6v','12v','15v'),
);
These subarrays will each be a dropdown Select list, an the end user can select exactly 1 from each of the select lists.
When the user hits submit, I will want to match the submitted values against a "price table" pre-defined by the admins. Potentially "red" and "6v" would cost $5, but "red" and "5"(length) and "6v" would cost $6.
The question is, how to do so?
Currently the approach I have taken is such:
Upon submission of the form (of the 3 select lists), I get the relevant price rules set by the admin from the database. I've made an example of results.
$data['price_table'] =
array(
'red;4'=>'2',
'red;5'=>'3',
'red;6'=>'4',
'blue;3'=>'5',
'blue;4'=>'6',
'blue;5'=>'7',
'blue;6'=>'8',
'green;3'=>'9',
'green;4'=>'10',
'green;5'=>'11',
'green;6'=>'12',
'purple;3'=>'13',
'purple;4'=>'14',
'purple;5'=>'15',
'purple;6'=>'16',
'red;3'=>'1',
'red;3;12v'=>'17',
'blue;6;15v'=>'18',
);
Note : The order of the above example can be of any order, and the algorithm should work.
I then explode each of the above elements into an array, and gets the result that matches the best score.
$option_choices = $this->input->post('select');
$score = 0;
foreach($data['price_table'] as $key=>$value)
{
$temp = 0;
$keys = explode(';',$key);
foreach($keys as $k)
{
if(in_array($k, $option_choices))
{
$temp++;
}else{
$temp--;
}
}
if($temp > $score)
{
$score = $temp;
$result = $value;
}
}
echo "Result : ".$result;
Examples of expected results:
Selected options: "red","5"
Result: 3
Selected Options: "3", "red"
Result: 1
Selected Options: "red", "3", "12v"
Result: 17
The current method works as expected. However, handling these using PHP is slow. I've thought of using JSON, but that would mean that I would be giving the users my whole price table, which isn't really what I am looking for. I have also thought of using another language, (e.g python) but it wouldn't particularly be practical considering the costs. That leaves me with MySQL.
If someone can suggest a cheap and cost-efficient way to do this, please provide and example. Better still if you could provide an even better PHP solution to this which works fast.
Thank you!
It looks like you did work to make the results read faster but you're still parsing and testing every array part against the full list? This would probably run faster moving the search to MySQL and having extra columns there.
Since you can control the array (or test string) perhaps try fixed length strings:
$results = explode("\n", "
1 Red v1
22 Blue v2
333 Green v3");
$i = 0;
while($i < count($results)) {
$a = substr($results[$i], 0, 10);
$b = substr($results[$i], 10, 20);
$c = substr($results[$i], strpos(' ', strrev($results[$i]))-1);
if(stripos($userInput, $a . $b . $c) !== false) {
// parse more...
Supposedly JavaScript is good at this with memoizaion:
http://addyosmani.com/blog/faster-javascript-memoization/