PHP get JsonArray from post [duplicate] - php

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 3 years ago.
I have this below JsonArray send from API, I want to save it to the database, but I can't get the data of the Array, always is a blank.
[{
"user": 7,
"states": true
}, {
"user": 13,
"states": true
}, {
"user": 10,
"states": false
}]
This is what I tried to get the JsonArray
if($_SERVER['REQUEST_METHOD']=='POST'){
$jsondata = json_decode(file_get_contents("php://input"),true);
$user= $jsondata['user'];
$status = $jsondata['states'];
$Query = "insert table(user,states,)
values ('$user','$status ')";
}
Thank You

$jsondata consist on multi dimensional array, your array looks like:
Array
(
[0] => Array
(
[user] => 7
[states] => 1
)
[1] => Array
(
[user] => 13
[states] => 1
)
[2] => Array
(
[user] => 10
[states] =>
)
)
And you are trying to insert without using any specific index or not using any loop.
Solution is that, you need to use loop here to store multiple rows in your database.
Second solution is that, you can store this data as same as it is, means, save data in json format in one column rather then to store in multiple rows and multiple column, whenever you need to fetch record or need to show your data, you can just use json_decode().
Side note: i hope (user,states,) last comma is just a typo here.

Related

Convert PHP array to chart.js compatible data [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 3 years ago.
Am using chart.js to display charts on my site. The working data attribute for chart.js is in this format
"data" => ['1', '2', '3']
I have my data currently in a PHP array
Array ( [0] => 1 [1] => 2 [2] => 3 )
However this is not working for my needs. How can I convert the PHP array into the same format as above?
I have tried
json_encode($myArray)
and
implode($myArray)
without success.
Any suggestions?
You could create an array with key "data" and another array as the value;
$myArray = ["data" => [1, 2, 3]];
echo json_encode($myArray);
Output
{"data":[1,2,3]}
Or put the values between quotes
$myArray = ["data" => ["1", "2", "3"]];
Output
{"data":["1","2","3"]}
Not sure completely understood the problem. But if you want to convert values of php array to a json you can do something like that:
json_encode(array_values($myArray));

How to extract array from $_POST

I am receiving POST data from a form that is an array along with a few other fields. I need to take the array data only and pass it along in a post request of my own to a backend server as json.
The $_POST data looks like this:
Array (
[smsgte_submit] => Y
[alias] => Array (
[1] => Array (
[name] => mywife
[number] => 6135552001
[ssid] => 1 )
[2] => Array (
[name] => daughter
[number] => 6135553001
[ssid] => )
)
)
I only want to capture the alias entries and encode them in json.
I was successful in encoding the entire $_POST array into json with:
$data['jsonpost'] = json_encode($_POST);
which encoded the array as expected, however, I only want the alias array, so I tried the following:
$data['jsonpost'] = json_encode($_POST['alias']);
That, however doesn't work, it returns null to the server. Then I tried:
$data['jsonpost'] = json_encode(array_filter($_POST, 'alias'));
But that returned null.
Maybe I need to redesign my form, but in the end, I want a json array that looks like this:
{
"alias": {
"name":"mywife",
"number":"6135552001",
"ssid":"1"
},
"alias": {
"name":"daughter",
"number":"6135553001",
"ssid":"2"
}
}
It turns out that the following syntax should be correct:
$data['jsonpost'] = json_encode($_POST['alias']);
However, in order to get it to work, I had to split it as follows:
$jsonpost = json_encode($_POST['alias']);
$data['jsonpost'] = jsonpost;
I switched back and forth between the two options a few times, but only the second one works, at least with PHP 7.3.5.

Collect all values from nested array row of specific key [duplicate]

This question already has answers here:
How to get an array of specific "key" in multidimensional array without looping [duplicate]
(4 answers)
Closed 1 year ago.
Need to create a list that consists of all values stored in the array row of a specific key (product_id). Currently, doing a print_r of my $bestsellers variable produces the following array:
Array
(
[0] => stdClass Object
(
[product_id] => 178
[order_item_qty] => 9
)
[1] => stdClass Object
(
[product_id] => 233
[order_item_qty] => 4
)
[2] => stdClass Object
(
[product_id] => 179
[order_item_qty] => 1
)
)
Other SO answers led me to try:
$ids = array_column($bestsellers, 'product_id');
...but that produced an empty array, I guess because the row I’m trying to grab is nested in there? With that in mind I tried
foreach($bestsellers as $bestseller) {
$ids = array_column($bestsellers, 'product_id');
}
...which produced no result at all.
Hopefully someone can help clue me in as to where I’m going wrong. Thanks!
The nested values are objects, not arrays (can't you see stdClass Object in the output?). array_column is for 2-dimensional arrays. You need to access the properties using object syntax.
$ids = array_map(function($x) { return $x->product_id; }, $bestsellers);
For future reference, array_column will work for this in PHP 7, so you must be using PHP 5.
For PHP 7, your code
$ids = array_column($bestsellers, 'product_id');
will do what you want it to.
See the difference here on 3v4l.org.

Getting only value from PHP JSON array (why do I have to use implode?)

Okay, so I'm fairly new to PHP but it's enough like JS so I've been picking it up fairly quickly.
One issue I ran into the other day was getting the values from a JSON file.
My JSON file is 30,000 lines, but here's essentially what it looks like:
{
"congress": {
"Brown Sherrod": [{
"birthday": "1952-11-09"
}, {
"gender": "M"
}, {
"type": "sen"
}, {
"state": "OH"
}, {
"party": "Democrat"
}],
...
And anyway, it continues like that for another 29,000 + lines. My code to get the contents of the JSON file is this:
$data = json_decode(file_get_contents('path/to/file/convertcsv.json'), true);
It returns an array like this:
Array (
[0] => Array (
[birthday] => 1952-11-09
)
[1] => Array (
[gender] => M
)
[2] => Array (
[type] => sen
)
[3] => Array (
[state] => OH
)
[4] => Array (
[party] => Democrat
)
)
My issue I ran into is that I can't get the value of, say, ['birthday'] without using implode().
This works: $state = implode($data['congress'][$nameInput][3]);, but this does not: $state = $data['congress'][$nameInput][3];
Is there a reason why? I've read the docs on implode() (join array elements with string) and from what I gather from SO and the PHP docs this is how you get the value, but why? It makes no sense to have to convert the array to a string in order to get the value. In JavaScript to get the value from an array (or even a key-value) you just use the ['key'] or the [index] of the array, and it'll give you the value.
I feel like either I'm goofing on something major (not unlikely) or PHP is just weird -- probably the former. So, to reiterate my question (because I can ramble) am I making this too complex or is PHP just weird (and if so, is there a reason)?
Try below :-
$state = $data['congress'][$nameInput][3]['state']

Php to json does not pass all arrays (or json does not display all received values)

As see for the first and the third row all fields filled, for the second row some fields left blank.
Filled values with
$.post("__php_file.php", { 'number_of_input_row': number_of_input_row, 'date_day': date_day, 'date_month': date_month, 'date_year': date_year, 'currency': currency }, function(data, success) {
$('#currency_load1').html(data[0].FinalCurrencyRate);
$('#currency_load2').html(data[1].FinalCurrencyRate);
$('#currency_load3').html(data[2].FinalCurrencyRate);
}, "json");
send to php file, process and get such php array
Array
(
[0] => Array
(
[CurrencyAbbreviation] => AUD
[DateOfCurrencyRate] => 2013-07-11
[NumberOfInputRow] => 1
[FinalCurrencyRate] => 0.506
)
[2] => Array
(
[CurrencyAbbreviation] => CAD
[DateOfCurrencyRate] => 2013-07-25
[NumberOfInputRow] => 3
[FinalCurrencyRate] => 0.516
)
)
json array is this
{
"0":{"CurrencyAbbreviation":"AUD","DateOfCurrencyRate":"2013-07-11","NumberOfInputRow":"1","FinalCurrencyRate":"0.506"},
"2":{"CurrencyAbbreviation":"CAD","DateOfCurrencyRate":"2013-07-25","NumberOfInputRow":"3","FinalCurrencyRate":"0.516"}
}
So far all ok. But below is described problem
Get back results and display here
<div id="currency_load1"></div>
<div id="currency_load2"></div>
<div id="currency_load3"></div>
However get displayed only FinalCurrencyRate for AUD or [0] => Array.
Question is: what need to correct to get displayed also FinalCurrencyRate from [2] => Array? As you see in php such array presents, but is not passed to json...
If fill all fields for the second row, then get displayed all three arrays.
Update Tried this
$('#currency_load1').html(data[0].FinalCurrencyRate);
$('#currency_load2').html("test to check");
$('#currency_load3').html(data[2].FinalCurrencyRate);
And all works. As understand within jquery need to create condition like if FinalCurrencyRate is empty, then $('#currency_load2').html("0");? But why such json/jquery behavior?

Categories