Convert JSON list to php array - php

I am passing a list of numbers from a page to PHP serialized in JSON
{"items":"[1,2,3,4]"}
in my URL it is just
...&items={"items":[1,2,3,4]}
I decode this in PHP
$json = $_GET["items"];
$arr = json_decode($json, true);
I get an array
Array ( [items] => [1,2,4] )
But when I try a foreach on arr["items"] and print out each value, all I get is a single value
[1,2,4]
This is the code I am using to iterate
foreach($res["items"] as $value)
echo $value;
How come I am not getting something like
1
2
4

Look closely at your json string:
{"items":"[1,2,3,4]"}
Look closer:
"[1,2,3,4]"
You are saying that items is a string containing:
"[1,2,3,4]"
Remove the " and you'll be fine.

Your serialization is wrong. Should be:
{"items":[1,2,3]}
To get rid of problems like that use JSON.stringify in JS:
var myData = {"items" : [1,2,3]},
queryString = 'data='+encodeURIComponent(JSON.stringify(myData));
for IE < 8 it has to be included from external script (see here) :
<!--[if lt IE 8]><script src="/js/json2.js"></script><![endif]-->
Anyway much easier would be to send it already as an array:
items[0]=1&items[1]=2&items[2]=3
This way you can send also more complex structures:
data[items][0]=1&data[items][1]=2
// on PHP side will become
$_GET['data'] = array('items' => array(1,2))

Related

How can I parse/extract from a string in PHP? Specifically something between quotes

I have a string like this
{"2":{"name":"Moon Center","value":"moon7","value_raw":"moon7","id":2,"type":"select"},"3":{"name":"Multiple Choice","value":"Second Choice","value_raw":"Second Choice","id":3,"type":"radio"}}
How do I get for example, the content inside value to a variable? And I would want to be able to get it for every item with value in there. There will be several that come from a form in a single string.
This is the response from a form that stores the whole string in a string. Kinda wish it was an array but this is what i'm working with.
Your string is actually a JSON value. To get the data out of it, you must first json_decode it to an array (or object). If you choose an array, you can then use array_column to get all the 'value' values:
$json = '{"2":{"name":"Moon Center","value":"moon7","value_raw":"moon7","id":2,"type":"select"},"3":{"name":"Multiple Choice","value":"Second Choice","value_raw":"Second Choice","id":3,"type":"radio"}}';
$array = json_decode($json, true);
print_r(array_column($array, 'value'));
Output:
Array (
[0] => moon7
[1] => Second Choice
)
Demo on 3v4l.org

how to fetch json fom url in php

I am trying to make a php page tp print json data for this i m using one paraeter for which i needed to fetch json from another url.I used the code given in other stackoverflow ans but it always giving 0.I tried everything but it always giving 0.My php code is:
<?php
if(isset($_POST['add']))
{
require_once('loginConnect.php');
$bookname=$_POST['bookname'];
$url = "http://example/star_avg.php?bookName=$bookname";
$json = file_get_contents($url);
$json_data = json_decode($json,TRUE);
echo 'data' + $json_data->results[0]->{'num'};
?>
My json data from other url is:
{"result":[{"avg":"3.9","num":"3"}]}
You see 0 printed because you're performing an addition + between the string data and a non-existent property. In PHP, to concatenate strings, do not use +; instead, use the dot . operator
In addition, because you're using true as the 2nd parameter to json_decode, what you get back is an array of arrays. Use the array notation [] rather than the object notation -> to access members.
$json_data = json_decode($json,TRUE);
$num = $json_data['result'][0]['num']; //<- array notation
echo 'data: '.$num; //prints data: 3
Live demo

PHP json_decode return empty array

I just test this sample from php doc (http://au2.php.net/manual/en/function.json-decode.php)
here is my code:
<?php $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; echo json_decode($json, true), '<br />';?>
But it just returns an EMPTY array.
Have no idea why...Been searching around but no solution found.
PLEASE help!
You can validate at following
website: http://jsonlint.com/
You have to use a php "json_decode()" function to decode a json encoded data.
Basically json_decode() function converts JSON data to a PHP array.
Syntax: json_decode( data, dataTypeBoolean, depth, options )
data : - The json data that you want to decode in PHP.
dataTypeBoolean(Optional) :- boolean that makes the function return a PHP Associative Array if set to "true", or return a PHP stdClass object if you omit this parameter or set it to "false". Both data types can be accessed like an array and use array based PHP loops for parsing.
depth :- Optional recursion limit. Use an integer as the value for this parameter.
options :- Optional JSON_BIGINT_AS_STRING parameter.
Now Comes to your Code
$json_string = '{"a":1,"b":2,"c":3,"d":4,"e":5}' ;
Assign a valid json data to a variable $json_string within single quot's ('') as
json string already have double quots.
// here i am decoding a json string by using a php 'json_decode' function, as mentioned above & passing a true parameter to get a PHP associative array otherwise it will bydefault return a PHP std class objecy array.
$json_decoded_data = json_decode($json_string, true);
// just can check here your encoded array data.
// echo '<pre>';
// print_r($json_decoded_data);
// loop to extract data from an array
foreach ($json_decoded_data as $key => $value) {
echo "$key | $value <br/>";
}
you should not use echo because it is an array. use print_r or var_dump .it works fine
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
print_r(json_decode($json, true));
Output:
Array
(
[a] => 1
[b] => 2
[c] => 3
[d] => 4
[e] => 5
)
No, it doesn't return an empty array.
Printing an array with echo just prints a string "Array()".
Use print_r or var_dump to get the structure of the variable.
In newer PHP it will also emit a notice when using echo on an array ("Array to string conversion"), so you shouldn't do it anyway. The manual you've mentioned changed to print_r.
It works fine, but you use wrong method to display array.
To display array you cannot use echo but you need to use var_dump
It works fine as others mention, but when you print the array it is converted to string, which means only the string "Array" will be printed instead of the real array data. You should use print_r(), var_dump(), var_export() or something similar to debug arrays like this.
If you turn on notices you will see:
PHP Notice: Array to string conversion in ...
The example you linked uses also var_dump for the same reason.
var_dump have pretty print in php5.4
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump( json_decode($json));

How to display this json in jquery

I not which part I am doing wrong. I couldn't able to fetch this array to display. Can someone please help me with this. I am new to JSON.
Array
(
[0] => [{"id":2,"request_id":2,"message":"wqvewq ewq wq ewq e wqwe qwe ","user_id":1,"created_at":"2014-05-30 16:21:28","updated_at":"2014-05-30 16:21:28"},{"id":3,"request_id":2,"message":"as aS A","user_id":2,"created_at":"2014-05-30 17:18:37","updated_at":"2014-05-30 17:18:37"},{"id":4,"request_id":2,"message":"AS As a","user_id":2,"created_at":"2014-05-30 17:18:43","updated_at":"2014-05-30 17:18:43"}]
[1] => [{"id":1,"request_id":2,"message":"sfsdfds sdfds f ","user_id":2,"created_at":"2014-05-30 17:15:16","updated_at":"2014-05-30 17:15:16"}]
[2] => []
)
The output you have quoted looks like PHP print_r output, and it's certainly not legal JSON.
Perhaps you need the PHP json_encode function, to get real JSON out of your PHP code?
It's not one json string but an array of json strings.
You have to first loop thru the array, parse the json and show the variables that you want in your html with jQuery.
You can find a lot of info on the internet and stackoverflow on this subject.
these are the possibilitys you have
var data = array();
for(var i=0;i<yourArray.length;i++)
data[i] = $.parseJSON(yourArray[i]);
or (untested)
var data = JSON.parse(JSON.stringify({yourArray: yourArray}));

php json_encode + modernizr object

I'm looking for better and more robust solution for echoing out yepnope feature tests using php. The output should look something like :
{
test : Modernizr.geolocation,
yep : 'normal.js',
nope : ['polyfill.js', 'wrapper.js']
}
From an output like:
$l10n = array(
'test' => 'Modernizr.geolocation',
'yep' => "'normal.js'",
'nope' => array("'polyfill.js'", "'wrapper.js'")
);
Obviously, there is the issue of quotation marks being wrapped around the json object. I can't help but wonder if there's a different class altogether that caters to creating mixed javascript objects containing raw javascript as well as strings.
json_encode returns the JSON representation of a value, the point is JSON representation is not a javascript object, JSON is a subset of the javascript object literal, so you need to do the convert in javascript.
var l10n = <?php echo json_encode($l10n); ?>;
if (l10n.test === "Modernizr.geolocation") {
l10n.test = Modernizr.geolocation;
}

Categories