I've been searching for a while now to accomplish my question, so I decided to ask it here.
My problem.
I've filled 2 arrays with content from a database like this:
$query = "SELECT table_1, table_2 FROM questions";
// Execute query or trow an error
$results = mysqli_query($conn, $query) or die(mysql_error());
$resulttablet1= array();
$resulttablet2= array();
while($row = mysqli_fetch_array($results))
{
// Add the right questions to the array
$resulttablet1[] = $row['table_1'];
$resulttablet2[] = $row['table_2'];
}
So I've now got 2 arrays, each filled with the content of one table. This is all working fine. Now I want to put those two arrays into one array so it acts like one big array.
Something like this:
$newarray = array();
$newarray[$resulttablet1, $resulttablet2];
or
$newarray = array($resulttablet1,
$resulttablet2);
Then I want to echo $newarray and show all the elements of the other two arrays.
I know I can echo both arrays separately, but this is not possible for the goal I'm trying to accomplish.
Thanks in advance.
Edit
I realise my question isn't clear enough, I'll try to explain it a bit better.
On top of my question I want to show the the content of both arrays one by one on button click. That's what I'm doing at the moment like this:
// I retrieve a value from a javascript file, where I add 1 to a variable each time a button is clicked then I send this value to the server using jQuery Ajax
$value = (int)$_POST["question_nmbr"];
// I use $value to echo the right element out of the array.
echo "<li>$resulttablet1[$value]</li>";
Everytime the button is clicked ajax loads the php file and the value is increased so the next question is loaded.
I want to do the same thing but now with an array which has multiple arrays inside of it.
array_merge doesn't do the trick I think, cause print_r($result); gives me all the content of the array.
I hope my question is a little bit more clear now.
I found the answer, thanks to someone who removed his answer already.
array_merge did the trick after all, I don't know what I did wrong the first time but now I can echo it just fine.
Here is how it works:
// I retrieve a value from a javascript file, where I add 1 to a variable each time a button is clicked then I send this value to the server using jQuery Ajax
$value = (int)$_POST["question_nmbr"];
$newarray = array_merge($resulttablet1, $resulttablet2);
echo "<li>$newarray[$value]</li>";
Hope someone will find this useful, if not ask for more info :)
Related
I am faced with a piece of code that does not make a lot of sense to me. I am working on a website using PHP and Smarty template, but there is one line of code regarding arrays that i do not understand how it works.
$SLang = &SLanguage::getInstance();
$q="SELECT * FROM texte where text_lang='{$SLang->lang}' ORDER BY text_id";
$texte = _sqlFetchQuery($q);
foreach($texte as $text)
{
$texteList[$text['text_alias']]['text'] = $text['text_text'];
if($text["text_category"]==3){
$philosophyList[] = $text["text_text"];
$philosophyListSeo[] = $text["text_alias"];
}
}
The output of "var_dump" on $philosophyList gets out only the "text_text" column from the database, and i do now understand the structure of how it gets there. Can someone care to explain? How does this particular line of code works? $texteList[$text['text_alias']]['text'] = $text['text_text'];
It's called a jagged array.
It's shorthand for this:
$texteList[$text['text_alias']] = array('text'=>$text['text_text']);
So it's creating a named array using whatever text is $text['text_alias'] brings out, and assigning as it's value an array with a named "text" element.
But this is irrelevant to $philosophyList[]. To understand how $philosophyList[] is working, you need to understand how foreach works; basically it takes each item in an array (in this case $texte) and assigns the value of that array item to a variable (in this case $text). This is just an easier way to do a for loop. They could just have easily done:
$philosophyList[] = $texte[$i]["text_text"];
I've created an array from a PHP session variable, and now I'm trying to use ajax (within jQuery) to remove an element from the array.
I've got the following code so far:
$val = $_SESSION['enquiry-basket'];
$array = explode($val);
foreach ($enquiries as $a => $q) {
if ($q == $_POST['product_id']) {
unset($array[$a]);
}
}
The only problem is, it doesn't remove the item.
Can anyone explain why, and tell me how to fix it?
Edit
Sorry guys. The reason I mentioned jQuery is because I use a jQuery ajax call to process the PHP I displayed above.
The ajax query runs fine because it processes some javascript goodies (remove's a div from the HTML) once the ajax returns a success.I've added the delimiter (can't believe I missed it) but the element doesn't get removed from the array still.
I've never been good at multi-dimensional arrays, so here's the array printed:
Array ( [0] => 6 [1] => 8 )
It looks right to me, but I'm an amateur in arrays. (6 and 8 are of course my strings I inserted)
explode is missing the first argument:
explode(',', $val);
You are removing item from $array, not from $_SESSION['enquiry-basket'].
The explode function should have two parameters. But you given only the name of the array.
explode(separator,string,limit);
If I understand correctly what you are trying to do, the problem is that JQuery runs client side, which means that your PHP arrays on the server side disappear between each request from Ajax. The only array that remains is $_SESSION.
If you want to use AJAX, you need to remove from $_SESSION directly. Anything else is just useless because the arrays and variables "disappear" between each call.
Mostly an issue with the explode function, the second parameter is missing:
Change from:
$array = explode($val);
To:
$array = explode('~',$val); // ~ is a delimiter
Trying to sort an array in PHP that is being populated from a CSV. I would also, ideally, LOVE to be able to control the sort by clicking on tabs in the table here .. Right now, though, my first task at hand is just sorting the damn thing.. been working on this for over 3 days now.. any help is GREATLY appreciated!! Cheers!
PHP
<?php
$fp = fopen("https://spreadsheets.google.com/pub?key=0AjZgwY03sLMGdHVoWjhucGowWWJBb2g2NnQzVG9HZFE&hl=en&single=true&gid=0&output=csv","r");
$rows = array();
while (($row = fgetcsv($fp)) !== FALSE) {
$rows[] = $row;
}
fclose($fp);
$headers = array_shift($rows);
foreach ($rows as $row) : list($ShowKey, $ShowFeedURL, $ShowLink, $ShowIcon, $ShowTitle, $ShowTag, $ShowCategory, $ShowEps, $ShowLastUpdate, $ShowNew) = $row;
$oddpost = ( empty( $oddpost ) ) ? '_odd' : ''; ?>
I recently did this. I had a multi-dimensional array of records from a database, and I needed to sort them based off of one specific column in the array. Here's what I did:
foreach($TimeRecords as $key => $value)
{
$Rates[$key] = $value['rate'];
}
array_multisort($Rates, SORT_ASC, $TimeRecords);
I build an array of only the column I need, then I use the array_multisort() function to sort the array based off of that column.
You can write functions that will do this in PHP and then just call them with javascript ajax calls and reload that part of the page when it's done sorting.
Instead of sorting the table in PHP, you may consider doing it client-side in Javascript. For instance have a look at this jQuery plugin: http://tablesorter.com/
You may find usort() function helpful. It accepts callback argument, which may be used for sorting by specific field.
I had a similar issue to this today. Basically what I ended up doing is creating a temporary table which I loaded in the rows from the csv file that I needed. From there, I used php to sort and organize the data and update or add to the table I needed to alter.
Example, I made a table called 'temp' and loaded in all the rows of the category I needed. Then, once this was in the table, I made a php script which sorted the information by number of total sales in descending order. From there, I did a query to update my main table and used a limit to control this (only the top 200 items by number of sales).
It was very easy to do and hopefully it will help you or someone else.
Keep in mind. If you're going to do this more than once, you will need to truncate the temporary table to remove the old rows first.
I have code in php such as the following:
while($r = mysql_fetch_array($q))
{
// Do some stuff
}
where $q is a query retrieving a set of group members. However, certain groups have there members saved in memcached and that memcached value is stored in an array as $mem_entry. To run through that, I'd normally do the following
foreach($mem_entry as $k => $r)
{
// Do some stuff
}
Here's the problem. I don't want to have two blocks of identical code (the //do some stuff section) nested in two different loops just because in one case I have to use mysql for the loop and the other memcached. Is there some way to toggle starting off the loop with the while or foreach? In other words, if $mem_entry has a non-blank value, the first line of the loop will be foreach($mem_entry as $k => $r), or if it's empty, the first line of the loop will be while($r = mysql_fetch_array($q))
Edit
Well, pretty much a few seconds after I wrote this I ended up coming with the solution. Figure I'd leave this up for anyone else that might come upon this problem. I first set the value of $members to the memcached value. If that's blank, I run the mysql query and use a while loop to transfer all the records to an array called $members. I then initiate the loop using foreach($members as as $k => $r). Basically, I'm using a foreach loop everytime, but the value of $members is set differently based on whether or not a value for it exists in memcached.
Why not just refactor out doSomeStuff() as a function which gets called from within each loop. Yes, you'll need to see if this results in a performance hit, but unless that's significant, this is a simple approach to avoiding code repetition.
If there's a way to toggle as you suggest, I don't know of it.
Not the ideal solution but i will give you my 2 cents. The ideal would have been to call a function but if you dont want to do that then, you can try something like this:
if(!isset($mem_entry)){
$mem_entry = array();
while($r = mysql_fetch_array($q))
{
$mem_entry[] = $r;
}
}
The idea is to just use the foreach loop to do the actual work, if there is nothing in memcache then fill your mem_entry array with stuff from mysql and then feed it to your foreach loop.
I'm new to programming and I'm tackling arrays. I thought I had multi-dimensional arrays figured out but I guess I don't. Here's the code I'm working on:
$loopcounter = 0;
while ($myrow = mysql_fetch_array($results)) {
//...other stuff happens...
$allminmax[$loopcounter][] = array("$myrow[3]","$currentcoltype","$tempmin","$tempmax");
$loopcounter++;
}
This chunk of code is supposed to create an array of four values ($myrow[3], currentcoltype, tempmin, tempmax) and insert it into another array every time the loop goes through. When I do this:
echo implode($allminmax);
I get:
ArrayArrayArrayArrayArrayArrayArrayArrayArray
Do I need to implode each array before it goes into the master array? I really want to be able to do something like $allminmax[0][4] and get the $tempmax for the first row. When I try this now nothing happens. Thanks -- any help is appreciated!
It looks like you should either use [$loopcounter] or [], but not both. You also should drop the quotes. They're unnecessary and in the case of "$myrow[3]" they interfere with the variable interpolation.
$allminmax[] = array($myrow[3], $currentcoltype, $tempmin, $tempmax);
By the way, arrays are zero-indexed, so to get $tempmax for the first row it'd be $allminmax[0][3] not $allminmax[0][4].
Also, a better way to display the contents of your array is with print_r or var_dump. These will display arrays within arrays while a simple echo will not.
var_dump($allminmax);