Store and retrieve a multidimensional array using php and mysql - php

I have a multidimensional array in PHP like this:
$array = array(
"Part1" => array(
"Subpart1" => array(0, 1),
"Subpart2" => array(1, 0)
),
"Part2" => array(0),
"Part3" => array(0, 1, 0)
);
Now I want to store this array in a MySQL table and retrieve it exactly like this again on another PHP page.
I've been trying using serialize() and unserialize()
$array= serialize($array);
and then on the other page
$array= $row['Array'];
$array2 = array();
$array2 = unserialize($array);
But I seem to do something wrong, in the beginning I got a var_dump of bool(false) and now I get a var_dump of NULL.

Your code looks ok...
One thing that can catch you out is if your column is too small - if you use VARCHAR(255) your data can be truncated and won't unserialize. If you add the value of $row['Array'] I could see if it's whole.

Use column type TEXT. Serialized data often doesn't fit VARCHAR(255).

You could use json encode, json_encode($array) and you will get a string value in json notation so you can store in database, and retrive and do a json_decode($string, true) so you cand convert in an array again. If you don't pass the true argument to the json_decode, it will converted to a stdClass.

Particulars
Quantity
Rate
Amount
Amount Sum
Others
Others Amount
Tax
Total
This is my table in php/html.
I need to store and retrieve the php Particulars(p),Quantity(q),Rate(r) as a separate table format

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)

How to select value from JSON array

I am trying to select a variable from an array (at least I think it's stored as an array):
$data = json_encode($response);
file_put_contents('file.txt', $data);
gives
"status":200,"response":{
"api_id":"0f42d6be-8ed2-11e3-822e-22135",
"bill_duration":36,
"call_duration":36,
"total_rate":"0.00300"}
}
How can I select the call_duration value (in php)? I've tried $response['call_duration'], which I thought should work but returns nothing?
$response['call_duration'] was very nearly correct, but I think you need:
$response['response']['call_duration']
Looking at your output after converting to json, I think the original array, $response, looks like this (in PHP array format)
$response = array(
'status'=>200,
'response'=>array(
'api_id'=>'0f....etc',
'bill_duration'=>36,
... etc
)
);
So, you need to go an extra level deep into the array to get call_duration.

What kind of php array is this and how do I edit it?

I am working with a project that is coded in php OOP. I have created a form that post back to itself and gets those values and puts them into a predefined array format. I say predefined because this is the way the previous coder has done it:
$plane->add(array('{"name":"Chris","age":"22"}','{"name":"Joyce","age":"45"}'));
So when I get my values from the $_POST array, I thought it would be simple, so I tried
$plane->add(array("{'name':$customerName,'age':$customerAge}"));
This is triggering an error though, it seems it's passing the actual name of the variable in as a string instead of it's value. So how do I pass those values in to that function. While we are on it, can someone explain what kind of array that is, I thought arrays were always $key=>value set, not $key:$value.
As other comments and answers have pointed out, the data is being serialized in a format known as JSON. I suggest reading up on json_encode() and json_decode()
To make your example work, you would have to do:
$data = array("name" => $customerName, "age" => $customerAge);
$plane->add(array(json_encode($data));
That looks like json:
http://sandbox.onlinephpfunctions.com/code/e1f358d408a53a8133d3d2e5876ef46876dff8c6
Code:
$array = json_decode('{"name":"Chris","age":"22"}');
print_r( $array );
And you can convert an array to json with:
$array = array("Customer" => "John");
$arrayJson = json_encode( $array);
So to put it in your context:
$array = array("Name"=>"Chris", "age" => 22);
$array2 = array("Name"=>"John", "age" => 26);
$plane->add(array( json_encode( $array),json_encode( $array2) );
It looks like it could be JSON, but might not be.
Be careful to quote everything like they have done, you didn't have any quotes around the name or age.
I've added the same sort of quotes, and used the backslashes so that PHP doesn't use them to end the string:
$plane->add(array("{\"name\":\"$customerName\",\"age\":\"$customerAge\"}"));
Be wary of user data, if $customerName and $customerAge come from POST data, you need to properly escape them using a well tested escaping function, not something you just hack together ;)
It looks like your array is an array of JSON encoded arrays. Try using:
$plane->add(array('{"name":"' . $nameVar . '","age":"' . $ageVar . '"}', ...));
If you use the following:
echo json_encode(array('name' => 'Me', 'age' => '75'), array('name' => 'You', 'age' => '30'));
You will get the following string:
[{"name":"Me","age":"75"},{"name":"You","age":"30"}]
I believe you are getting an error because what you are trying to pass to the function is not JSON while (It looks like ) the function expects an array json strings, Manually trying to write the string might not be a good idea as certain characters and type encode differently. Best to use json_encode to get you json string.
$plane->add(array(json_encode(array('name'=>$customerName,'age'=>$customerAge))));

php: get array value without iterating through it?

hey guys,
i think i lost my mind.
print_r($location); lists some geodata.
array (
'geoplugin_city' => 'My City',
'geoplugin_region' => 'My Region',
'geoplugin_areaCode' => '0',
'geoplugin_dmaCode' => '0',
'geoplugin_countryCode' => 'XY',
'geopl ...
when I iterate through it with a foreach loop I can print each line.
However shouldn't it be possible to just get a specific value out of the array?
like print $location[g4]; should print the countryCode shouldn't it? Thank you!
echo $location['geoplugin_countryCode'];
Yes, you can get a specific value by key. The keys in your case are the geoplugin_ strings.
To get the country code:
// XY
$location['geoplugin_countryCode'];
$location['geoplugin_countryCode'];
would access country code
Where does "g4" come from? Did you mean "4"?
If you had a normal numerically-indexed array then, yes, you could write $location[4]. However, you have an associative array, so write $location['geoplugin_countryCode'].
there you are using an associative array, it is an array with a user defined key:value pair (similar to dictionaries on Python and Hash Tables on C#)
You can access the elements just using the Key (in this case geoplugin_city or geoplugin_region)
Using the standard array syntax:
$arrayValue = $array[key]; //read
$array[key] = $newArrayValue; //write
For example:
$location['geoplugin_city']; or $location['geoplugin_region'];
If you are not familiarwith PHP arrays you can take a look here:
http://php.net/manual/en/language.types.array.php
For a better understanding on array manipulation with PHP take a look of:
http://www.php.net/manual/en/ref.array.php

I would like json_encode in PHP to return a JSON array even if the indices are not in order

but according to this: http://www.php.net/manual/en/function.json-encode.php#94157 it won't.
I'm using flot so I need to have an array with numeric indexes returned but what I'm getting is this:
jsonp1282668482872 ( {"label":"Hits 2010-08-20","data":{"1281830400":34910,"1281916800":45385,"1282003200":56928,"1282089600":53884,"1282176000":50262,"1281657600":45446,"1281744000":34998}} );
so flot is choking. If I var_dump the array right before I call json_encode it looks like this:
array(7) {
[1281830400]=>
int(34910)
[1281916800]=>
int(45385)
[1282003200]=>
int(56928)
[1282089600]=>
int(53884)
[1282176000]=>
int(50262)
[1281657600]=>
int(45446)
[1281744000]=>
int(34998)
}
any ideas?
As zneak says, Javascript (and thus JSON) arrays cannot have out-of-order array keys. Thus, you either need to accept that you'll be working with JSON objects, not arrays, or call array_values before json_encode:
json_encode(array_values($data));
However, it looks like you're looking to display time series data with flot. As you can see on the flot time series example, it should be a two element array like so:
$.plot(
$('#placeholder'),
[[
[1281830400, 34910],
[1281916800, 45385],
[1282003200, 56928],
[1282089600, 53884],
[1282176000, 50262],
[1281657600, 45446],
[1281744000, 34998]
]],
{
label: 'Hits 2010-08-20',
xaxis: {mode: 'time'}
}
)
Given your array (let's call it $data) we can get the proper JSON like so:
json_encode(
array_map(
function($key, $value) { return array($key, $value); },
array_keys($data),
array_values($data)
)
);
It's conceptually impossible. You cannot encode an array with fixed indices in JSON.
As a reminder, a JSON array looks like this:
[1, 2, 3, 4, 5]
There's no room to put indices there.
You should work on the Javascript side. Accepting that json_encode will return an object, you can convert this object into an array. That shouldn't be too hard.
function toArray(object)
{
var result = [];
for (var key in object)
{
if (!key.match(/^[0-9]+$/)) throw new Error("Key must be all numeric");
result[parseInt(key)] = object[key];
}
return result;
}
You can force json_decode() to produce arrays by passing TRUE as the second parameter, but you can't force json_encode() to produce arrays in the first place:
json_decode($json, TRUE); // force array creation
You can use array_merge to reindex a numerically indexed array, like this:
$a = array(2 => 3, 4 => 5);
$a = array_merge($a);
var_dump($a);
For flot, what you're asking for isn't actually what you want. You want an array of arrays, not an array of numbers. That is, you want something that looks like this:
[[1281830400, 34910],
[1281916800, 45385],
[1282003200, 56928],
[1282089600, 53884],
[1282176000, 50262],
[1281657600, 45446],
[1281744000, 34998]]
As for how to do that in PHP, I'm not sure.

Categories