How to use json and php - php

I'm new to JSON, but I have experience in PHP. Can someone explain to me how JSON works, especially with PHP, and EASY way would be nice.
EX: I have a php array like:
array(
array('id' => 1, 'img' => "http.img1.png", 'title' => 'ice cream'),
array('id' => 2, 'img' => "http.img2.png", 'title' => 'silly snail'),
array('id' => 3, 'img' => "http.img3.png", 'title' => 'big bear'),
array('id' => 4, 'img' => "http.img4.png", 'title' => 'Funny cat'),
);
is this fine, or should I alter this array? I want to convert this to a JSON Object. In the php array should there be a parent, and do I have to assign array elements as children, or can each php obj be it's own JSON obj? Thank you!

Just run json_encode on the variable that you want to turn into a json string.
$something = array("test" => array("value", "another value", 4));
echo json_encode($something)
This will produce
{"test":["value","another value",4]}
Also, putting that string into $something = json_decode("{"test":["value","another value",4]}"); will produce back the same array that was passed into json_encode.
Note that JSON is not a programming language; it is a way to represent objects. http://json.org has a complete visual representation of how to use it. JSON's main components are Arrays (surrounded by []) and Objects (surrounded by {}). Arrays are lists of comma separated values (see json.org for how to tell it the types...its pretty simple) while objects are key:value pairs separated by commas between each pair where they key is a string surrounded by quotation marks. Above I created an Object with a key called "test" whose value was an Array with two strings and a number in it.

Use json_encode() for encoding the array, get the array back by using json_decode().

Related

post string and array using curl [duplicate]

This question already has answers here:
How to create an array for JSON using PHP?
(8 answers)
Closed 1 year ago.
I am using a plugin that requires an array of associative rows as a json formatted string -- something like:
[
{oV: 'myfirstvalue', oT: 'myfirsttext'},
{oV: 'mysecondvalue', oT: 'mysecondtext'}
]
How do I convert my multidimensional array to valid JSON output using PHP?
Once you have your PHP data, you can use the json_encode function; it's bundled with PHP since PHP 5.2.
In your case, your JSON string represents:
a list containing 2 elements
each one being an object, containing 2 properties/values
In PHP, this would create the structure you are representing:
$data = array(
(object)array(
'oV' => 'myfirstvalue',
'oT' => 'myfirsttext',
),
(object)array(
'oV' => 'mysecondvalue',
'oT' => 'mysecondtext',
),
);
var_dump($data);
The var_dump gets you:
array
0 =>
object(stdClass)[1]
public 'oV' => string 'myfirstvalue' (length=12)
public 'oT' => string 'myfirsttext' (length=11)
1 =>
object(stdClass)[2]
public 'oV' => string 'mysecondvalue' (length=13)
public 'oT' => string 'mysecondtext' (length=12)
And, encoding it to JSON:
$json = json_encode($data);
echo $json;
You get:
[{"oV":"myfirstvalue","oT":"myfirsttext"},{"oV":"mysecondvalue","oT":"mysecondtext"}]
By the way, from what I remember, I'd say your JSON string is not valid-JSON data: there should be double-quotes around the string, including the names of the objects' properties.
See http://www.json.org/ for the grammar.
The simplest way would probably be to start with an associative array of the pairs you want:
$data = array("myfirstvalue" => "myfirsttext", "mysecondvalue" => "mysecondtext");
then use a foreach and some string concatenation:
$jsontext = "[";
foreach($data as $key => $value) {
$jsontext .= "{oV: '".addslashes($key)."', oT: '".addslashes($value)."'},";
}
$jsontext = substr_replace($jsontext, '', -1); // to get rid of extra comma
$jsontext .= "]";
Or if you have a recent version of PHP, you can use the json encoding functions built in - just be careful what data you pass them to make it match the expected format.
This is one of the most fundamental rules in php development:
DO NOT MANUALLY BUILD A JSON STRING.
USE json_decode().
If you need to populate your data in a loop, then gather all of your data first, then call json_encode() just once.
Do not try to wrap/prepend/append additional data to an encoded json string. If you want to add data to the json payload, then decode it, add the data, then re-encode it.
It makes no difference if you pass object type or array type data to json_encode() -- by default, it will still create a string using square braces for indexed arrays and curly braces for iterable data with non-indexed keys.
Code:
$array = [
[
'oV' => 'myfirstvalue',
'oT' => 'myfirsttext'
],
[
'oV' => 'mysecondvalue',
'oT' => 'mysecondtext'
]
];
echo json_encode($array);
Output:
[{"oV":"myfirstvalue","oT":"myfirsttext"},{"oV":"mysecondvalue","oT":"mysecondtext"}]
For clarity, I should express that the OP's desired output is not valid json because the nested keys are not double quote wrapped.
You can use the stdClass, add the properties and json_encode the object.
$object = new stdClass();
$object->first_property = 1;
$object->second_property = 2;
echo '<pre>';var_dump( json_encode($object) , $object );die;
VoilĂ !
string(40) "{"first_property":1,"second_property":2}"
object(stdClass)#43 (2) {
["first_property"]=>
int(1)
["second_property"]=>
int(2)
}
This is the php code to generate json format.
while ($row=mysqli_fetch_assoc($result))
{
$array[] = $row;
}
echo '{"ProductsData":'.json_encode($array).'}'; //Here ProductsData is just a simple String u can write anything instead

Multidimensional Array Not Echoing As Expected

I am setting this array manually:
$schools = array(
'Indiana University'=>array(
'initials'=>'IU',
'color'=>'red',
'directory'=>'indiana'
)
);
But it won't echo "IU" when I use:
echo $schools[0][0];
It does show correctly when I do:
print_r($schools);
I'm sure I'm messing up something dumb, but I have no idea what and I've been staring at it for hours. This array is actually part of a larger array with multiple universities, but when I trim it down to just this, it doesn't work.
PHP arrays support two types of keys - numerical and strings.
If you just push a value onto an array, it will use numerical keys by default. E.g.
$schools[] = 'Indiana University';
echo $schools[0]; // Indiana University
However, when you use string keys, you access the array values using the string key. E.g.
$schools = array(
'Indiana University' => array(
'initials' => 'IU',
'color' => 'red',
'directory' => 'indiana'
)
);
echo $schools['Indiana University']['initials']; // UI

Encode associative array as valid php

Is there a way to encode variables as strings that can be evaluated as php code? In particular, I'm interested in associative arrays. (Scalar values and indexed arrays are encoded as valid php code by json_encode. I don't need to encode objects and resources).
$Array = ['1', 2, 'key' => 'value'];
php_encode($Array); // => "[0 => '1', 1 => 2, 'key' => 'value']" or similar
You can use var_export with the second parameter set to true:
function php_encode($val)
{
return var_export($val, true);
}
http://php.net/manual/en/function.var-export.php

PHP dump variable as PHP code

I'm looking for a function to dump a multi-dimension array so that the output is valid php code.
Suppose I have the following array:
$person = array();
$person['first'] = 'Joe';
$person['last'] = 'Smith';
$person['siblings'] = array('Jane' => 'sister', 'Dan' => 'brother', 'Paul' => 'brother');
Now I want to dump the $person variable so the the dump string output, if parsed, will be valid php code that redefines the $person variable.
So doing something like:
dump_as_php($person);
Will output:
$person = array(
'first' => 'Joe',
'last' => 'Smith',
'siblings' => array(
'Jane' => 'sister',
'Dan' => 'brother',
'Paul' => 'brother'
)
);
var_export()
var_export() gets structured
information about the given variable.
It is similar to var_dump() with one
exception: the returned representation
is valid PHP code.
serialize and unserialize
This is useful for storing or passing PHP values around without losing their type and structure. In contrast to var_export this will handle circular references as well in case you want to dump large objects graphs.
The output will not be PHP code though.

Generate json string from multidimensional array data [duplicate]

This question already has answers here:
How to create an array for JSON using PHP?
(8 answers)
Closed 1 year ago.
I am using a plugin that requires an array of associative rows as a json formatted string -- something like:
[
{oV: 'myfirstvalue', oT: 'myfirsttext'},
{oV: 'mysecondvalue', oT: 'mysecondtext'}
]
How do I convert my multidimensional array to valid JSON output using PHP?
Once you have your PHP data, you can use the json_encode function; it's bundled with PHP since PHP 5.2.
In your case, your JSON string represents:
a list containing 2 elements
each one being an object, containing 2 properties/values
In PHP, this would create the structure you are representing:
$data = array(
(object)array(
'oV' => 'myfirstvalue',
'oT' => 'myfirsttext',
),
(object)array(
'oV' => 'mysecondvalue',
'oT' => 'mysecondtext',
),
);
var_dump($data);
The var_dump gets you:
array
0 =>
object(stdClass)[1]
public 'oV' => string 'myfirstvalue' (length=12)
public 'oT' => string 'myfirsttext' (length=11)
1 =>
object(stdClass)[2]
public 'oV' => string 'mysecondvalue' (length=13)
public 'oT' => string 'mysecondtext' (length=12)
And, encoding it to JSON:
$json = json_encode($data);
echo $json;
You get:
[{"oV":"myfirstvalue","oT":"myfirsttext"},{"oV":"mysecondvalue","oT":"mysecondtext"}]
By the way, from what I remember, I'd say your JSON string is not valid-JSON data: there should be double-quotes around the string, including the names of the objects' properties.
See http://www.json.org/ for the grammar.
The simplest way would probably be to start with an associative array of the pairs you want:
$data = array("myfirstvalue" => "myfirsttext", "mysecondvalue" => "mysecondtext");
then use a foreach and some string concatenation:
$jsontext = "[";
foreach($data as $key => $value) {
$jsontext .= "{oV: '".addslashes($key)."', oT: '".addslashes($value)."'},";
}
$jsontext = substr_replace($jsontext, '', -1); // to get rid of extra comma
$jsontext .= "]";
Or if you have a recent version of PHP, you can use the json encoding functions built in - just be careful what data you pass them to make it match the expected format.
This is one of the most fundamental rules in php development:
DO NOT MANUALLY BUILD A JSON STRING.
USE json_decode().
If you need to populate your data in a loop, then gather all of your data first, then call json_encode() just once.
Do not try to wrap/prepend/append additional data to an encoded json string. If you want to add data to the json payload, then decode it, add the data, then re-encode it.
It makes no difference if you pass object type or array type data to json_encode() -- by default, it will still create a string using square braces for indexed arrays and curly braces for iterable data with non-indexed keys.
Code:
$array = [
[
'oV' => 'myfirstvalue',
'oT' => 'myfirsttext'
],
[
'oV' => 'mysecondvalue',
'oT' => 'mysecondtext'
]
];
echo json_encode($array);
Output:
[{"oV":"myfirstvalue","oT":"myfirsttext"},{"oV":"mysecondvalue","oT":"mysecondtext"}]
For clarity, I should express that the OP's desired output is not valid json because the nested keys are not double quote wrapped.
You can use the stdClass, add the properties and json_encode the object.
$object = new stdClass();
$object->first_property = 1;
$object->second_property = 2;
echo '<pre>';var_dump( json_encode($object) , $object );die;
VoilĂ !
string(40) "{"first_property":1,"second_property":2}"
object(stdClass)#43 (2) {
["first_property"]=>
int(1)
["second_property"]=>
int(2)
}
This is the php code to generate json format.
while ($row=mysqli_fetch_assoc($result))
{
$array[] = $row;
}
echo '{"ProductsData":'.json_encode($array).'}'; //Here ProductsData is just a simple String u can write anything instead

Categories