php multidimensional array encode and decode json - php

I have an array what I encode as json and I save it to database. The array looks like
$myarray = array(
'test'=>array('key1'=>'1',
'key2'=>'2',
'key3'=>'3'),
'test2' =>array('key4'=>'1',
'key5'=>''
)
);
json_encode($myarray);
the saved json in my database looks like
{
"test": {"key1":"1",
"key2":"2",
"key3":"3"
},
"test2": {"key4":"1",
"key5":""
}
}
MYSQL save
$sql = "UPDATE my_table SET params= '".json_encode($param )."' WHERE id ='".$key."'";
Than when I retrieve the json string from database and trying to rebuild the array with json_decode($json, true); outputs null

You could serialize the data rather than storing it as json.
$sql = "UPDATE table SET field='".serialize($myarray)."' WHERE ...";
Then when you want to recreate the array, just pull it out of the table and unserialize() it. It's not human readable in the database; however this technique is fast and works well for storing arrays in the db. If the data is needed by your js scripts then json_encode() it after you unserialize() it.

Have you tryed to use addslashes() and stripslashes() php functions ?
Try:
To update your table:
$sql = "UPDATE my_table SET params='".addslashes(json_encode($myarray))."' WHERE id ='".$key."';";
to read from table:
$sql = "SELECT params FROM my_table WHERE id='".$key."';";
...code to read row...
$myparams = stripslashes($row['params']);
also you can try the a custom function for a multidimensional array from php manual called stripslashes_deep() see http://www.php.net/manual/en/function.stripslashes.php (EXAMPLE #2)
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
// Example
$array = array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));
$array = stripslashes_deep($array);
print_r($array);
// Output
Array
(
[0] => f'oo
[1] => b'ar
[2] => Array
(
[0] => fo'o
[1] => b'ar
)
)

Related

How to assign array to array variable which is store in a database

I store array structure in database table.
example
table name - example
id=1
data= array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43")
I want to get that array structure from table and assign data column to an array.
Example
while($row=mysqli_fetch_array($result))
{
$table=$row['data'];
}
I did this way.. but it's not working.
It results in:
$table[0]=>array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43")
You can save array data to database field in multiple ways.
I suggest two ways:
1) Serialized array:
you can save data using serialize() function.
e.g. $arr = array('234' => 'asfdads', 'asdf' => 'asdf2');
$toDb = addslashes(serialize($arr));
And then you can unserialize() them to get it back like:
$toDb = unserialize(stripslashes($fromDb));
2) Using json_encode() and json_decode();
e.g. $arr = array('234' => 'asfdads', 'asdf' => 'asdf2');
$toDb = json_encode($arr);
And then you can json_decode() them to get it back like:
$toDb = json_decode($fromDb)

Edit value in a json from an array

I hav an array like this:
Array
(
[fruit] => Banana
[country] => Canada
)
How can I update my json file with a loop with these new datas ?
My json is a file and it looks lile this:
{"fruit" : "Cherry", "country" : "Mexico", "weight" : "28"}
Note: I want to update the value fruit and country, not all the json.
Thanks.
As i said you can decode your json as an associative array (note the use of json_decode() with second parameter set on true), loop throw it and update it while iterating. Finally encode to json again as follow
$array = array('fruit' => 'Banana', 'country' => 'Canada');
$json = '{"fruit" : "Cherry", "country" : "Mexico", "weight" : "28"}';
$mjson = json_decode($json,true);
foreach($array as $key => $val) {
if(isset($mjson[$key])) {
$mjson[$key] = $val;
}
}
$jjson = json_encode($mjson);
print_r($jjson);
//Output: {"fruit":"Banana","country":"Canada","weight":"28"}
Live demo
$input = /** some json string **/
$json = json_decode($input, true); // to assoc array
// update values
$json["fruit"] = "Cherry";
$json["country"] = "Mexico";
$json["weight"] = "28";
$ouput = json_encode($json); // back to json
// save to file etc.
Does this help?
You can't directly edit the file like it is an object.
First you need to read the file, than decode json:
e.g:
$string='{"name":"John Adams"}';
$json_a=json_decode($string,true);
Remember if you use second parameter "true" in json_a you will get associative array. Something like this:
$json_a=array("name"=>"John Adams");
But if you want to have an object don't set second parameter:
$string='{"name":"John Adams"}';
$json_o=json_decode($string);
Here json_decode($string) returns an object. Now you can do this:
echo $json_o->name;
When you modify the json object, write it back to the file.

store array in the database

I have three arrays example: $array1,$array2,$array3.
I want to insert the array2 and array3 in two different columns in the same table.
can i do that?
here is the code below that i am trying but it does not work for me i am doing in codeigniter:
controller:
$athletes_id = $this->input->post('athletes'); // array 1
$fields_id = $this->input->post('fields_id'); // array 2
$athlete_score = $this->input->post('athlete_score'); // array 3
$id = array();
foreach($athlete_score as $row){
$additional_data = array(
'test_reports_id' => $test_report_id,
'score' => $row,
);
$id[] = $this->test_model->save_test_reports_details($additional_data);
}
for($j=0;$j<count($fields_id);$j++){
$data2 = array('fields_id' => $fields_id[$j]);
$this->test_model->update_test_reports_details($id,$data2);
}
Model :
public function update_test_reports_details($id,$data2){
$this->db->where_in('id',$id);
$this->db->update('test_reports_details',$data2);
}
Just serialize the arrays.
$data2 = serialize($array2); // or whatever array you want to store
Then to retrieve with unserialize
$array2 = unserialize($data2);//or the row index
To store array in database you have to serialize it.
Try :
public function update_test_reports_details($id,$data2){
$this->db->where_in('id',$id);
$this->db->update('test_reports_details',serialize($data2));
}
To unserialize it when you get it from the database you have to use unserialize()
You can serialize as suggested in other answers, however I personally prefer to json_encode the array.
$data = json_encode($array);
And when you are reading in the model you should decode the data:
$array = json_decode($data, true); // set second argument to true to get an associative array
Using JSON has the advantage of better readability while still in the DB. This might not seem like much, but it can really help in some cases.

unserialize array

I am return a serialize array from a post meta field in wordpress called groups.
here is how it looks in to post meta field.
a:2:{i:0;s:1:"1";i:1;s:1:"2";}
how can i loop trough this and run an if statement i.e.
$mydata = unserialize($meta['groups']);
print_r($mydata);
The unserialzed isnt working for me the ouput i get from the print_r is below
a:2:{i:0;s:1:"1";i:1;s:1:"2";}
which is same as above.
Any help on working with serialized and unserialzed arrays never used before.
Propably magic_quotes is active. Strip the slashes generated by it with stripslashes:
$mydata = unserialize(stripslashes($meta['groups']));
If you want to strip slashes from the whole GPC-Array use this (Credits go to this comment on PHP.net):
if (get_magic_quotes_gpc()) {
$strip_slashes_deep = function ($value) use (&$strip_slashes_deep) {
return is_array($value) ? array_map($strip_slashes_deep, $value) : stripslashes($value);
};
$_GET = array_map($strip_slashes_deep, $_GET);
$_POST = array_map($strip_slashes_deep, $_POST);
$_COOKIE = array_map($strip_slashes_deep, $_COOKIE);
}
print_r(unserialize('a:2:{i:0;s:1:"1";i:1;s:1:"2";}'));
will print
Array
(
[0] => 1
[1] => 2
)
The unserialization works just fine. How do you know if $meta['groups'] contains what you want?
Here is what I obtained using command-line PHP:
php > $x = unserialize('a:2:{i:0;s:1:"1";i:1;s:1:"2";}');
php > print_r($x);
Array
(
[0] => 1
[1] => 2
)
It seems that $meta['groups'] does not contain the serialized string.

PHP json_encode return rows as arrays instead of objects

From my experience, when I json_encode data from a mysql table, the output is an object containing each row as an object within. What I want to do is to get each row as an array, like the example below (don't need the column names in there). How can I do that?
{ "Data": [
["1","Internet Explorer 4.0","Win 95+","4","X","1"],
["2","Internet Explorer 5.0","Win 95+","5","C","2"],
["3","Internet Explorer 5.5","Win 95+","5.5","A","3"],
["4","Internet Explorer 6","Win 98+","6","A","4"],
] }
Use mysql_fetch_row [docs] to get each row. This will get a row as a numerical array and those are also encoded as JSON arrays:
$data = array();
while(($row = mysql_fetch_row($result))) {
$data[] = $row;
}
echo json_encode(array('Data' => $data));
NOT CHECKED in interpreter:
You can change the type of variable by simple types convertion:
$data = DB::get('SELECT * FROM `table` WHERE 1');
echo json_encode(array('Data' => (array)$data));
Also you can use next function: array mysql_fetch_array ( resource $result [, int $result_type ] )

Categories