How to store MySql values as Multidimensional Array using PHP - php

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.

Related

Adding serialized data to an array - PHP

I have a three serialized data structures.
a:2:{i:0;s:151:"[["1","0","0","1","0","0","1","0","1","0","0","0"],["1","0","0","0","1","0","0","0","1","0","1","1"],["1","0","1","0","1","0","1","0","1","0","0","1"]]";i:1;s:151:"[["1","0","1","0","1","0","1","0","1","0","1","0"],["1","0","1","0","1","1","0","1","0","1","0","1"],["1","0","1","0","1","0","1","1","1","0","1","1"]]";}
a:2:{i:0;s:163:"[["10","0","0","0","30","0","0","60","0","0","0","0"],["20","0","0","30","0","0","20","0","0","0","50","0"],["30","0","0","0","20","0","0","30","0","20","0","30"]]";i:1;s:154:"[["20","0","0","0","0","0","0","0","0","0","0","0"],["30","0","0","0","0","0","0","0","0","0","0","0"],["40","0","0","0","0","0","0","0","0","0","0","0"]]";}
a:4:{i:0;s:151:"[["1","0","0","1","0","0","1","0","1","0","0","0"],["1","0","0","0","1","0","0","0","1","0","1","1"],["1","0","1","0","1","0","1","0","1","0","0","1"]]";i:1;s:151:"[["1","0","1","0","1","0","1","0","1","0","1","0"],["1","0","1","0","1","1","0","1","0","1","0","1"],["1","0","1","0","1","0","1","1","1","0","1","1"]]";i:2;s:151:"[["1","1","1","0","1","1","1","0","0","0","1","1"],["1","1","1","0","0","1","1","1","1","0","1","1"],["1","1","1","1","0","0","1","1","1","1","1","1"]]";i:3;s:151:"[["1","0","1","0","0","0","1","0","1","0","0","2"],["1","0","0","2","1","0","1","0","1","1","0","1"],["1","0","2","1","1","1","0","1","0","1","1","1"]]";}
I want to add all three serialized data into a single serialized array.
I tried this code and its work, but I want to be able to add additional data.
$data2=unserialize($value['monthly_forecast']);
$data1=unserialize($temp['monthly_forecast']);
//print_r($data1);
$combinedData = array($data1, $data2);
$monthly_forecast=serialize($combinedData);
$temp['monthly_forecast']=$monthly_forecast;
What about unserialize then array_merge() and then serialize the merged array back? Note that array_merge() can be used to
Merge one or more arrays
so you should be able to apply it in your case.
Edit:
You have a couple of options. You can either unserialize and merge everything into a single array and then serialize that. Or, you can also:
$array = array($serialized_data_1, $serialized_data_2, $serialized_data_3);
$all_serialized = serialize($array);
And then, to access the data:
$all_unserialized = unserialize($array);
$unserialized_data_1 = unserialize(all_unserialized[0]);
$unserialized_data_2 = unserialize(all_unserialized[1]);
$unserialized_data_3 = unserialize(all_unserialized[2]);

Convert JSON string from database to PHP array problems

I am trying to convert this JSON string into a PHP array. The JSON string is stored in my database and I have already retrieved it.
{
"users": "user1, user2"
}
I need to convert the above JSON string into an array like the following but dynamically.
$myArray = array("user1", "user2")
This is my code:
$row = mysqli_fetch_array($result);
$json = $row['json'];
$decode = json_decode($json);
$list = $decode->users;
$myArray = explode(',', $list);
This code doesn't work in my program but when I print the array with print_r it looks identical to if I print $myArray from the nondynamic string. This is a concern because the nondynamic string works.
The separator between the usernames is comma+space, you're just using comma when you explode, so the second and following usernames are getting a space at the beginning. Try:
$myArray = explode(', ', $list);
I recommend that you change the JSON structure so you store an actual array, rather than a comma-separated list.
{
"users": ["user1", "user2"]
}
Even better would be to change your database structure so the users are in a real table, rather than being wrapped in JSON. This would allow you to perform queries that search for users easily and efficiently.

Serialized multidimensional stored in MySQLi does not print past first array

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.

Storing mysqli_query into multidimensional php array and utilizing that array as input to highcharts

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.

PHP/MYSQL array storing and retrieval issue

I want to store short arrays in a field. (I realize there are reasons to break the array up into items and store separately, but I'm opting for a simple storage option at the expense of less capability.)
My code to create the array is as follows:
$str = "one,two,three,four";
$array = explode (",",$str)
I then store into a text field in mysql using an insert statement It seems to store fine. In PhPAdmin, it shows ARRAY in the field and if I just echo $array, it prints "ARRAY".
The problem is occurring when I try to retrieve data.
I am retrieving using
while($row = mysql_fetch_array($res)) {
$array = $row['list']; //that's the field it is stored in
echo $array; // echoes "ARRAY"
//so far so good. However, when I then try to print out the contents of the array, I get error messages. I have tried using implode and also for each.
$text = implode(",", $array);//yields error message improper argument in implode function
foreach($array as $val) {
echo $val;
} //yields error message improper argument for for each statement
}
Could my entry in the dbase not be a proper array? What could the problem be? Thanks for any suggestions.
The usual approach to storing an array in this way is to serialize the data before input, and unserialize it upon retrieval.
$array = array('one', 'two', 'three', 'four');
$stringToStore = serialize($array);
Later:
while($row = mysql_fetch_array($res)) {
$array = unserialize($row['list']);
var_dump($array);
}
What you're inserting is not an array, just what PHP has evaluated your array as being in string form. To store an array in MySQL without properly normalizing your data you'll need to serialize it. Basically you'd want to do something like:
$serialized = implode(',', $arrayToStore);
and then store that in MySQL. On its way out then you'll do:
$unserialized = explode(',', $arrayFromMySQL);
I think you can use serialize and also (if you don't use serialize) if your array string is as follows
$str = "one,two,three,four";
then why you are making it an array before inserting it into your database, I think you can insert the string directly and when you need to use your string as an array then you can simply retrieve the string from database and make it an array using explode like
while($row = mysql_fetch_array($res)) {
$array = explode(",", $row['list']); // "one,two,three,four"
echo $array[0]; // one

Categories