PHP - trying to make a JSON-like array and getting confused - php

I am using PHP and trying to create an array that looks something like this:
{
"aps" : {
"alert" : "Hey"
},
"custom_control" : {
"type" : "topic_comment",
"object":{
"topic_id":"123",
"topic_section":"test"
"plan_id":"456"
}
}
}
So far I have something like
$message = array('aps'=>array('alert'=>$some_variable));
but I am getting confused how I can put the values for "custom_control" into this array after that. Could anyone please advise how to do that from my existing php?
Thanks!

Is this what you mean?
<?php
$some_variable = "Hey";
$myArray = array(
"aps" => array(
"alert" => $some_variable
),
"custom_control" => array(
"type" => "topic_comment",
"object" => array(
"topic_id" => "123",
"topic_section" => "test",
"plan_id" => "456"
)
)
);
?>

Here is an easy way to discover what you need to do.
Create your JSON object.
Use it as input to the json_decode function.
Use the output of this as the input to var_export()
So supposing you assigned your JSON to $json_object, then use:
var_export(json_decode($json_object, true));

If you are more comfortable building the object in JSON you can use the JSON parser included in php. Also, JSON defines Javascript objects, not arrays (although you can define arrays in JSON with something like {myArray : [1,2,3]}
Try this if you want though:
http://php.net/manual/en/function.json-decode.php

If you've already created your initial message array (per your question), you would then do something like this.
$message["custom_control"] = array(
"type" => "topic_comment",
"object" => array(
"topic_id" => "123",
"topic_section" => "test",
"plan_id" => "456"
)
)
You can create whatever nodes you needs inside of $message this way.

What you are trying to create is not an array, but rather an object.
Try to not build it as an array but an object.
$obj = new stdClass();
$obj->aps = new stdClass();
$obj->aps->alert = 'Hey';
$obj->custom_control = new stdClass();
$obj->custom_control->type = 'topic_comment';
$obj->custom_control->object = new stdClass();
$obj->custom_control->object->topic_id = '123';
$obj->custom_control->object->topic_section = 'test';
$obj->custom_control->object->plan_id = '456';
$json = json_encode($obj);

$array = array();
$array['aps'] = "alert";
$array['custom_control'] = array();
$array['custom_control']['type'] = "topic_comment";
$array['custom_control']['object'] = array('topic_id' => '123',
'topic_section' => 'test',
'plan_id' => '456');

i think you need something like this:
$message =array( "aps" =>array("alert"=>"Hey"),
"custom_control" => array(
"type" => "topic_comment",
"object" => array(
"topic_id"=>"123",
"topic_section"=>"test",
"plan_id"=>"456"
)
)
);

Related

How to put array to obj in php?

I have an json obj:
$response["data"][] = array("ID" => $comment["ID"]);
I put to new obj like this:
array_push($response["username"],"abc");
and it return like this:
{"data":[{"ID":"2106"}],"username":"123"}
but I want to like this:
{"data":[{"ID":"2106","username":"123"}]}
How can I do it?
Maybe you mean this:
{"data":[{"ID":"2106", "username":"123"}]
BTW you need
array_push($response["data]["username"],"abc");
Maybe you want:
$response["data"][] = array("ID" => $comment["ID"], 'username' => '123');
Please note that you can always simplify your code to make it more readable by creating variables.
$row = array(
'ID' => $comment['ID'],
'username' => '123'
);
$response['data'][] = $row;

PHP & JSON: Inserting an array in a nested array

I am creating a JSON structure to be passed back to Ajax. I would like to insert 'para' => "Hello" into "content" like this:
{
"sections": {
"content": [{
"para": "Hello"
}]
}
}
I tried using this code:
$array = array('sections' => array());
array_push($array["sections"], array("content" => array())); // content must be initialized as empty
array_push($array["sections"][0], array("para" => "Hello"));
But I received this instead:
{
"sections": [{
"content": [],
"0": {
"para": "Hello"
}
}]
}
If I try array_push($array["sections"]["content"], array("para" => "Hello")), I get an error instead. How do I insert an array into "content"? What am I doing wrong?
If I understood your intentions correctly, here's the array structure you're aiming for:
array("sections" => array(
"content" => array("para" => "Hello"),
));
However, in Javascript [] represents an array and {} represents an object. If you're trying to create an object with a property of "0", that's not possible in PHP. Variable names have to start with a letter or underscore.
Here's an array of content objects:
$content = new stdClass();
$content->para = 'hello';
array("sections" => array(
"content" => array($content),
));
To add arrays of contents:
array("sections" => array(
"content" => array(
array("para" => "Hello"),
array("para" => "Hello"),
array("para" => "Hello"),
),
));
You can also construct your own contents array first if you're iterating over an index and then json_encode it. Basic example:
$content = array();
for (i=0; i <3; i++) {
$content[] = array('para' => 'hello');
}
json_encode(array("sections" => array(
"content" => array($content),
)));
To convert that to JSON, put your array inside a json_encode() call.
$array['sections'] = array("content" => array(array("para" => "Hello")));
echo json_encode($array);
will give the result in desired format

I want to convert sting ( associative array sting ) into associative array?

i want to store associative array into a variable a as a string, and then convert the variable into array.
$var='"electirc_bill"=>array(
"type" => "number",
"required"=>"yes"
),
"electirc_bill_per"=>array(
"type" => "number",
"required"=>"yes"
),
"gass_bill"=>array(
"type" => "number",
"required"=>"yes"
)
)';
var_dump($var);
Use serialize and unserialize.
Convert the array to string:
$string = serialize($array);
Convert it back to an array:
$array = unserialize($string);
Edit: Based on your comment you seem to already have the array stored as a string and want to be able to convert it to an array. For that I would use eval but be cautious when using it with any user input as it could lead to security vulnerabilities within your code.
I've made a small example using your code here: http://codepad.org/rPNXPBlW
$var = '$array_var = array("One" => array("1.1", "1.2"), "Two" => array("2.1", "‌​2.2"));';
eval($var);
echo $array_var['One'][0]; // Shows 1.1
Use like below,
$json_str = json_encode($var);
first then use json_decode($json_str); where required
// save
file_put_contents('file.json', json_encode($array));
// load
$array = json_decode(file_get_contents('file.json'), true);
You can use serialize and unserialize like this:
<?
$var=array("electirc_bill"=>array(
"type" => "number",
"required"=>"yes"
),
"electirc_bill_per"=>array(
"type" => "number",
"required"=>"yes"
),
"gass_bill"=>array(
"type" => "number",
"required"=>"yes"
)
);
var_dump($var);
$string = serialize($var);
var_dump($string);
$array = unserialize($string);
var_dump($array );
?>
WORKING CODE
Here i give suggestion to use this array will meet your requirement
$name=array('parent1'=>array('childone'=>'harish','childtwo'=>'vignesh'),'parent2'=>array('childone'=>'our children'));
echo "<pre>";
print_r($name);
foreach($name as $parents)
{
foreach($parents as $child)
{
echo "<pre>"; print_r($child);
}
}

Parsing JSON from PHP

I'm trying to iterate in a JSON object that is returned from a PHP script. The return part is something like:
$json = array("result" => -1,
"errors" => array(
"error1" => array("name" => "email","value" => "err1"),
"error2" => array("name" => "pass","value" => "err2")
)
);
$encoded = json_encode($json);
echo $encoded;
So, in JavaScript I can do:
var resp = eval('(' + transport.responseText + ')');
alert(resp.length);
alert(resp.errors.error1.name);
But I can't do:
alert(resp.errors.length);
I would like to iterate errors, that's why I'm trying to get the length. Can somebody give me a hint? Thanks!
To be able to do that, you need resp.errors to be a Javascript array, and not a Javascript object.
In PHP, arrays can have named-keys ; that is not possible in Javascript ; so, when using json_encode, the errors PHP array is "translated" to a JS object : your JSON data looks like this :
{"result":-1,"errors":{"error1":{"name":"email","value":"err1"},"error2":{"name":"pass","value":"err2"}}}
Instead, you would want it to look like this :
{"result":-1,"errors":[{"name":"email","value":"err1"},{"name":"pass","value":"err2"}]}
Notice that "errors" in an array, without named-keys.
To achieve that, your PHP code would need to be :
$json = array(
"result" => -1,
"errors" => array(
array("name" => "email","value" => "err1"),
array("name" => "pass","value" => "err2")
)
);
$encoded = json_encode($json);
echo $encoded;
(Just remove the named-keys on errors)
Have a look at your JSON output. resp.errors will be something like this:
{"error1": {"name": "email", "value": "err1"}, ...}
As you can see, it's an object, not an array (since you passed it an associative array and not an numerically indexed array.) If you want to loop through an object in JavaScript, you do it like this:
for (var error in resp.errors) {
alert(resp.errors[error].name);
}
If you want it to be a JavaScript array, your PHP should look like this:
$json = array("result" => -1, "errors" => array(
array("name" => "email","value" => "err1"),
array("name" => "email","value" => "err1")
));
If you inspect the evaluated object in Firebug, you would see that "errors" is not an array but an object(associated arrays in PHP translates to object in JS). So you need to use for-in statement to iterate through an object.
You need to check every property name with hasOwnProperty to be sure that it is something you have sent, not some prototype property.

Transform string from associative array into multidimensional array

I'm storing images links into the database separating them with ,, but I want to transform this string into an array, but I'm not sure how to do it.
So my array looks like this:
$array = array(
"name" => "Daniel",
"urls" => "http:/localhost/img/first.png,http://localhost/img/second.png"
);
So I'd like to have it in the following form:
$array2 = array(
"name" => "Daniel",
"urls" => array("http:/localhost/img/first.png",
"http://localhost/img/second.png" )
);
I haven't been PHP'ing for a while, but for that simple use-case I would use explode.
$array['urls'] = explode(',', $array['urls']);
Uncertain if I interpreted your question correct though?
You can use array_walk_recursive like in the following example.
function url(&$v,$k)
{
if($k=='urls') {
$v = explode(",",$v);
}
}
$array = array(
"name" => "Daniel",
"urls" => "http:/localhost/img/first.png,http://localhost/img/second.png"
);
array_walk_recursive($array,"url");
You can check the output on PHP Sandbox

Categories