How to Convert the below string into the array using php - php

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);

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

Convert a PHP string array into an Array object

I'm developing a PHP app and I have a problem by converting a string array into an object array. I tried to force casting my string into an array by using (array), but it won't works. Here is my string (debug):
string '['method'=>'post','action'=>'#']' (length=32)
As you can see, it's a perfect array into a string and i want to convert that string.
My question is simple, does PHP has a function to convert directly a string into an array (I think no) or i have to convert my string by using explode?
From php 5.4 you can simply eval:
eval("\$f=['method'=>'post','action'=>'#'];");
var_dump($f);
For olders you have to fix the string a bit, change the 1st "[" to "array(" and the last "]" to ")".
The question is a bit duplicate of How to create an array from output of var_dump in PHP?
Here is how you define an array.
But before writing code, please take a look at manuels
$arrayName = array('method' => 'post', 'action' => '#');
The output will read
array (size=2)
'method' => string 'post' (length=4)
'action' => string '#' (length=1)
You can use preg_split and foreach() to make this work:
$str = "['method'=>'post','action'=>'#']";
$splitArray = preg_split("/[,']+/", $str);
foreach ($splitArray as $k => $val) {
if ($val == '=>') {
$newArr[$splitArray[$k - 1]] = $splitArray[$k + 1];
}
}
var_dump($newArr);
/*newArr
Array
(
[method] => post
[action] => #
)*/

Parsing JSON data with php - Data coming back empty

I have a piece of JSON that I'm parsing with php. I need to get one of the pieces of data out of it.
Here's the output of the json when I do a print_r:
Array ( [deviceId] => 07a9727e-3fe5-4f44-9765-134388241f39 [programId] => 3895 [serviceId] => 19977 [createdAt] => 2013-12-12T07:19:04.466Z [updatedAt] => 2013-12-12T07:19:04.466Z [objectId] => 7TxmL2GiXq )
Here's my code trying to extract deviceId:
$objectData = json_decode($data, true);
print_r($objectData);
$deviceId = $objectData->deviceId;
$deviceId is coming back empty.
Any help would be appreciated. Thanks.
Do this:
$deviceId = $objectData['deviceId'];
You are using the optional second parameter TRUE in your json_decode call, which converts it into an associative array instead of an object.
Alternatively:
$objectData = json_decode($data);
$deviceId = $objectData->deviceId; // Works

Array manipulation

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.

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