Hey I am stuck in the middle of my code. I am getting some input data from my partner and I get an array. At the 0 index of the array there are 3 strings. The array looks like this
array
0 =>
object(MunichInnovationGroup\PatentBundle\Entity\PatentIdJson)[1405]
private 'patentId' => string 'EP.02708872.A' (length=13)
private 'jsonData' => string '{"ops:world-patent-data": {
"#xmlns": {
"ops": "http://ops.epo.org",
"$": "http://www.epo.org/exchange",
"ccd": "http://www.epo.org/ccd",
"xlink": "http://www.w3.org/1999/xlink"
},
"ops:meta": {
"#name": "elapsed-time",
"#value": "69"
}
private 'status' => string 'Found' (length=5)
What I am interested in is the 'jsonData' String. Can I covert this whole array to a multidimensional array or just get the 'jsonData' and convert it into an array so that I get the information what I need from the 'jsonData'.
Thanks
what you need is json_decode and you can do the following:
$jsonObject = json_decode($myArray[0]->getjsonData(), true);
That will generate an object from the jsonData your partner is providing in the array
Based on your comment, you can get to the data using:
$jsonData = $your_array[0]->getjsonData();
Assuming that the MunichInnovationGroup\PatentBundle\Entity\PatentIdJson extends the MunichInnovationGroup\PatentBundle\Entity class.
Related
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
How to convert the below string into array using php
String : "[{\"site_id\":1,\"posts\":{\"0\":146,\"2\":104,\"3\":80},\"groups\":[{\"group_id\":1,\"site_id\":1,\"group_name\":\"Default List\",\"posts\":{\"0\":146,\"2\":104,\"3\":80}}]}]"
php code: json_decode(string, true);
I am using above code to convert the string into an array, still no use
can know to how to convert the string into the array
I want to get the posts id from the string.
It seems that your String is JSON -
so you could translate that JSON into the appropriate datatype in php simply by using the built int json_decode function
http://php.net/manual/de/function.json-decode.php
$json = "['a','b','c']";
var_dump(json_decode($json), true);
produces
array(3) {
[0] => 'a',
[1] => 'b',
[2] => 'c'
}
$jsonData = "[{\"site_id\":1,\"posts\":{\"0\":146,\"2\":104,\"3\":80},\"groups\":[{\"group_id\":1,\"site_id\":1,\"group_name\":\"Default List\",\"posts\":{\"0\":146,\"2\":104,\"3\":80}}]}]";
$data = json_decode($jsonData);
I'm looking for a way to access this JSON file data. What I'm interested in is to extract the property named documentjsonblob, as below.
object(Quadrem\Model\Order)[201]
protected '_dateCreated' => null
protected '_buyerCode' => null
array (size=2)
2415 =>
array (size=23)
'#storeid' => string '813' (length=3)
'#active' => string '1' (length=1)
'#created' => string '2013-11-25 12:28:21' (length=19)
'documentjsonblob' => string '{"HEAD":{"ORDERSEQUENCE":"0","TOTAL_TAX":7.9,"TOTAL_AMOUNT":86.9,"NUMBER":"AKMon3","TYPE":"NB","TYPE_NAME":"Standard PO","SUPPLIER":"0000002122","CREATED":"2013-04-29T12:00:00Z","CONTRACT_NUMBER":"","EXTERNAL_REFERENCE":"","CONTACT_PERSON":"Caroline Howlett","COMMENT":[""],"CURRENCY":"AUD","DELIVERY_TERMS":"DeliveryCondition|","PAYMENT_TERMS":[{"TEXT1":"21st day of next month after receipt"}],"NET_VALUE":79.0,"DELIVERY_ADDRESS":{"NAME_1":"KGTP FACILITY","NAME_2":"GAS TREATMENT PLANT","NAME_3":"KGPF","POSTAL_CODE":"6714","CITY":"Karratha","STREET":"Withnell Bay","REGION":"AUWA","REGION_NAME":"AUWA","COUNTRY":"AU"}]}' (length=3029)
'documenttype' => string 'PO' (length=2)
1890 =>
array (size=23)
'#storeid' => null
'#active' => null
I'm not quite sure which kind of an encoded JSON file this is by the way it looks. Would appreciate it if somebody could help.
Thanks.
Since in the comment you have mentioned it is the out put of var_dump and you want to get documentjsonblob, let's follow this:
On first line you have object(Quadrem\Model\Order)[201], that means you var_dumped an object, say $my_obj
On line four array (size=2) says you have an array, and what you need is located in the first element of the array, so $my_obj[0]
$my_obj[0] holds an associative array, and the desired index is documentjsonblob, so we can get the String representation as:
$my_arr = $my_obj[0];
$json_str = $my_arr['documentjsonblob'];
Now $json_str holds the String representation, to convert it to an PHP object:
$json_obj = json_decode($json_str);
So now $json_obj holds the object you want.
i have a json array wherer i would like to pasre the json till the last element by using for loop for that i would like to get the number of array elements in the json array ,i have more than 3 objects in anarray ,so i am confused how to parse the json till the last element,
i can say you the idea
Count($json);
echo count;
for(i=0;i<l=count($json);i++)
{
then print the value of each key
}
i am stuck ,because there is no fixed lenght for the json i am getting as it is a server response it may return one object one may be twice or thrice or many ,so i thought it would be better to do with for loop ,as a json contain more than one json with 3 keys ,such as country can have more than one state,and one state can have more than one district ,plaese help me,i am stuck with question for last 2 days
thank you
An idea :
function printJson($json) {
foreach($json as $index=>$value) {
if(is_array($value)) {
printJson($value);
} else {
echo 'Value :'.$value.'<br />';
}
}
}
$stringJson = "{'location':[{...}]}"; //for example
printJson(json_decode($stringJson));
You can alternatively decode the json tring using json_decode() which will give u a php variable which u can then easily iterate over using php.
eg.
$string = '{"image":"fox.png","puzzlepieces":{"f":{"puzzlepiece":"one","position":"top:121px;left:389px;"},"x":{"puzzlepiece":"three","position":"top:164px;left:455px;"},"o":{"puzzlepiece":"two","position":"top:52px;left:435px;"}}}';
var_dump(json_decode($string));
will output as
object(stdClass)[1]
public 'image' => string 'fox.png' (length=7)
public 'puzzlepieces' =>
object(stdClass)[2]
public 'f' =>
object(stdClass)[3]
public 'puzzlepiece' => string 'one' (length=3)
public 'position' => string 'top:121px;left:389px;' (length=21)
public 'x' =>
object(stdClass)[4]
public 'puzzlepiece' => string 'three' (length=5)
public 'position' => string 'top:164px;left:455px;' (length=21)
public 'o' =>
object(stdClass)[5]
public 'puzzlepiece' => string 'two' (length=3)
public 'position' => string 'top:52px;left:435px;' (length=20)
My xdebug extension is on in WAMP so your var_dump might be a little differently formatted but overall you'd get a php variable from the array which u can iterate using foreach or other loops.
Read more on json_decode here
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