I have a table that is listed like this:
Table name: test
|--------------------|
|------Column 1------|
|--------------------|
|John,Raul,Matt,Tyler|
|Tim,Hannah----------|
|Zeke,Brady,Tim,Tyler|
|Elliot,Zeke---------|
|Matt,Andrew,Idda----|
...
And I need to get all of those names into a PHP array, without multiple cases of the same name.
Would I be better off getting each unique name via SQL, or should I just pull the column, and then parse through it via PHP?
The final PHP array would look like:
$test_array[0]="John"
$test_array[1]="Raul"
$test_array[2]="Matt"
$test_array[3]="Tyler"
$test_array[4]="Tim"
$test_array[5]="Hannah"
$test_array[6]="Zeke"
$test_array[7]="Brady"
$test_array[8]="Elliot"
$test_array[9]="Andrew"
$test_array[10]="Idda"
I'm not sure how I would parse each cell in the table. What would you guys do?
I agree it's best to normalize the database. However, given the situation you've described, I would perform the SQL select and use PHP to run through the results.
I'd initialize $results as an empty string:
$results = '';
Then I'd concatenate each row with $results:
$results .= $row;
Then I'd use explode() to put all of the names in an array:
$all_names = explode(',', $results);
Then I'd use array_unique() to reduces the $all_names array to unique values:
$unique_names = array_unique($all_names);
HTH.
Related
I have a script that loops through and retrieves some specified values and adds them to a php array. I then have it return the value to this script:
//Returns the php array to loop through
$test_list= $db->DatabaseRequest($testing);
//Loops through the $test_list array and retrieves a row for each value
foreach ($test_list as $id => $test) {
$getList = $db->getTest($test['id']);
$id_export[] = $getList ;
}
print(json_encode($id_export));
This returns a JSON value of:
[[{"id":1,"amount":2,"type":"0"}], [{"id":2,"amount":25,"type":"0"}]]
This is causing problems when I try to parse the data onto my android App. The result needs to be something like this:
[{"id":1,"amount":2,"type":"0"}, {"id":2,"amount":25,"type":"0"}]
I realize that the loop is adding the array into another array. My question is how can I loop through a php array and put or keep all of those values into an array and output them in the JSON format above?
of course I think $getList contains an array you database's columns,
use
$id_export[] = $getList[0]
Maybe can do some checks to verify if your $getList array is effectively 1 size
$db->getTest() seems to be returning an array of a single object, maybe more, which you are then adding to a new array. Try one of the following:
If there will only ever be one row, just get the 0 index (the simplest):
$id_export[] = $db->getTest($test['id'])[0];
Or get the current array item:
$getList = $db->getTest($test['id']);
$id_export[] = current($getList); //optionally reset()
If there may be more than one row, merge them (probably a better and safer idea regardless):
$getList = $db->getTest($test['id']);
$id_export = array_merge((array)$id_export, $getList);
My session variables are
$_SESSION["listofIds"]=163,164;
$_SESSION["listofVals"]=4,3;
I want to select session values like
$_SESSION["listofIds"][0]=163;
$_SESSION["listofIds"][1]=164;
$_SESSION["listofVals"][0]=4;
$_SESSION["listofVals"][1]=3;
I tried
echo $_SESSION["listofIds"][0];
then it prints '1' i.e. first character. How can I handle this?
Also how can I get 1st element of $_SESSION["listofIds"] and 1st element of $_SESSION["listofVals"] after placing in while loop for mysql query.
Your session variables seem to be strings. Use
$IdsArr = explode(",", $_SESSION["listofIds"]);
echo $IdsArr[0];
With explode splitting the string by "," to an array.
$listofIds = array();
$listofIds = explode(",",$_SESSION["listofIds"]);
now you can access the variables using listofIds[0] or listofIds[1].
First of all you should start by defining from scratch an array while placing values in the $_SESSION array. This is a better way to write code.
Anyway as all the other answers said:
$listofIds = array();
$listofIds = explode(",",$_SESSION["listofIds"]);
will convert your string into an array and you will be able to access each value in different ways. Most commons:
using a foreach loop
getting the index of the item you want to use.
If you want to use the first item in a query you should get its value using the index (array starts from 0) so your value will be $listofids[0]. The same logic will apply to the other $_SESSION value.
Another good practice for programming: when you put an array value in a query string assign it to a variable before:
$id_to_search = $listofids[0];
and then use it into the query:
$sql = "SELECT * FROM your_table WHERE id='$id'";
This will save you a lot of headache with singe and double quotes.
Confusing title, the basics are that I'm saving a fully sorted and ordered multidimensional array from a script and into MySQL. I then, on another page, pull it from the database and unserialize it, and then proceed to print it out with this,
$s = "SELECT * FROM gator_historical_data WHERE channelid = '{$chanid}'";
$r = $link->query($s);
$comboarray = array();
while ($row = mysqli_fetch_assoc($r)) {
$comboarray[] = unserialize($row['dataarray']);
}
foreach ($comboarray as $item) {
$desc = $item['content']['description'];
$title = $item['content']['title'];
$datetime = $item['datetime'];
// ... ^^^ problems getting array data
}
The problem is that it doesn't take the full array from MySQL, only the first entry and thus only prints the first 'array'. So where the returned value from dataarray looks like this (var_dump): http://pastebin.com/raw.php?i=Z0jy55sM the data stored into the unserialized $comboarray only looks like this (var_dump): http://pastebin.com/raw.php?i=Ycwwa924
TL;DR: Pulling a serialized multidimensional array from a database, unserializing and it loses all arrays after the first one.
Any ideas what to do?
The string you've got is a serialized string plus something more at the end that is also a serialized string again and again:
a:3:{s:6:"source";s:25:"World news | The Guardian";s:8:"datetime ...
... story01.htm";}}a:3:{s:6:"source";s:16:"BBC News - World";
^^^
This format is not supported by PHP unserialize, it will only unserialize the first chunk and drop everything at the end.
Instead create one array, serialize it and store that result into the database.
Alternatively you can try to recover for the moment by un-chunking the string, however in case the paste was done right, there are more issues. But on the other hand the paste obvious isn't the done fully correct.
I have a question on saving mysqli_fetch_array into multidimensional php array,I have month and amount as data, ex January-12345.0987,February-87654.3456 etc, I am able to get the data from database and able to store it as two different arrays, but I would like to store it in single one and then I want to use that array to send input to highcharts. Can any one please suggest me, below is the code I used for storing the retrieved data into two different arrays
$month=array();
$amount=array();
$i=0;
while($user_data = mysqli_fetch_array($data))
{
//echo 'inside while loop';
$month[$i]=$user_data['month'];
$amount[$i]=$user_data['monthavg'];
$i++;
//$month[$i][$i]=$user_data['month']['monthavg'];
}
I should either use a two dimensional array (the boring way)
$records = mysqli_fetch_all($data);
// Access array of attributes of the first row
var_dump($records[0]);
// Access attribute 'month' of first row
var_dump($records[0]['month']);
// Access attribute 'monthavg' of first row
var_dump($records[0]['monthavg']);
or objects (the cool way):
$records = array();
while($record = mysqli_fetch_object($data))
{
$actualData[] = $record;
}
// Access array of attributes of the first row
var_dump($records[0]);
// Access attribute 'month' of first row
var_dump($records[0]->month);
// Access attribute 'month' of first row
var_dump($records[0]->monthavg);
Then write your JSON or CSV response for your highchart JavaScript app:
$out = fopen('php://output', 'w');
fputcsv($out, $records);
fclose($out);
I recommned you to prepare correct array structure in the php, then use json_encode(). In the javascript use $.getJSON() and load your data. As a result you avoid csv / loading files and parsing it again.
I have a database table as follows.
<table border='1'><th>Id</th><th>FirstName</th><th>last Name</th><tr><td>1</td><td>Tom</td><td>T</td></tr><tr><td>2</td><td>Jerry</td><td>J</td></tr></table>
I would like to store all values as a multi dimensional array using php(using a while loop to retrieve fields).That is,
I would like the data to be echoed as:
array(array(1,Tom,T),array(2,Jerry,J));
$result = mysql_query("SELECT * FROM tablename;");
while($result_ar = mysql_fetch_array($result)) {
$multid_array[] = $result_ar;
}
after which $multid_array will be an array of arrays.
You can use phps serialize function to convert any variable into a string representation
$string = serialize($dbData);
You can use unserialize() to convert the string back into arrays, objects, etc
$dbData = unserialize($string);
Once you have the data within a string, it's very easy to store in a file, db, etc. A disadvantage is that you won't be able to search your database easily for this data.