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

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

Related

Cannot iterate over array after json_decode(file_get_contents(filename))

I want to write an Array as JSON into a file. Then i want to get the content, decode it and iterate over the array. The Problem is i cannot iterate over the Array that i get from the file. What am i doing wrong?
var_dump() shows the array.
<?php
$array = array(
array("Artikel" => "Bananen",
"Menge" => 10,
"id" => "4711"
),
array("Artikel" => "Eier",
"Menge" => 1,
"id" => "abc"
)
);
file_put_contents("daten.json", json_encode($array));
$array1 = json_decode(file_get_contents("daten.json"));
var_dump($array1);
for($i=0; $i<count($array1); $i++){
echo $array1[$i]["Menge"];
echo "<br>";
}
?>
If you run your code, you will get the error Cannot use object of type stdClass as array.
This is because when json_encode is executed, the nested arrays are interpreted as an objects.
If you write:
$array1 = json_decode(file_get_contents("daten.json"), true);
then the objects will be converted to arrays and everything will work as expected.

how do I get my php array to json

I'm trying to make my json output in the following format below, but I do not know how to code it to make it display in just format... I just have the values, any kind of help I can get on this is greatly appreciated!
{
"firstcolumn":"56036",
"loc":"Deli",
"lastA":"Activity",
"mTime":"2011-02-01 11:59:26.243",
"nTime":"2011-02-01 10:57:02.0",
"Time":"2011-02-01 10:57:02.0",
"Age":"9867 Hour(s)",
"ction":" ",
"nTime":null
},
{
"firstcolumn":"56036",
"loc":"Deli",
"lastA":"Activity",
"mTime":"2011-02-01 11:59:26.243",
"nTime":"2011-02-01 10:57:02.0",
"Time":"2011-02-01 10:57:02.0",
"Age":"9867 Hour(s)",
"ction":" ",
"nTime":null
}
You can use a PHP associative array to set the key => value's of your array to be converted to json. As you would expect the key of the php associative array becomes the key of the JSON object, and the same with the values.
$array = array(
'firstcolumn' => '56036',
"loc" => "Deli",
"lastA" => "Activity",
"mTime" => "2011-02-01 11:59:26.243",
"nTime" => "2011-02-01 10:57:02.0",
"Time" => "2011-02-01 10:57:02.0",
"Age" => "9867 Hour(s)",
"ction" => "",
"nTime" => NULL
);
You can do both arrays like this (using previous array to show concept but can replace with that same array())
$array2 = $array1;
$array2['firstcolumn'] = "56037";
$botharrays = array($array, $array2);
What we just did is put both sub arrays into one containing array so that when you encode the json it has each object separately.
array( array1, array2 )
Then use json_encode() to encode the array into the json format you requested
$JSON= json_encode($array);
or
$json = json_encode($botharrays);
I think you are looking for this:
$json = json_encode($myArray);
print_r($json);

How to add this data to array ? Json

I have an array as such
$array = array{
'title' => "happy"
}
When i use Json encode, i get :
{"title":"happy"}
Later on in my code, i need to add some items in the $array like "Gender"
$array[] = array{
'Gender' => $gender
}
When i use Json encode, it becomes something like:
{"title":"happy","0":{"Gender":"female"}}
I really don't want the "0". I just want it to be :
{"title":"happy","Gender":"female"}
What am i doing wrong ?
You are creating a new array and then appending it to the end of the existing array.
You just want to add a new key to the existing array:
$array['Gender'] = $gender;
Do like this,
$array = array('title' => "happy");
$array['Gender'] = $gender;
json_encode($array);
DEMO
First you assign a filled array to $array. Later you add another array to the existing array.
Creating an array with content:
$array = array(
'title' => 'happpy'
);
Is the same as:
$array = array();
$array['title'] = 'happy';
When adding an extra value to the array you need to:
$array['gender'] = 'Your gender';
After the full array is created you can json_encode it.
Tip:
Merge two existing arrays by using the function array_merge().
$array[] = array('title' => "happy");
echo json_encode($array)."</br>";
//outputs : [{"title":"happy"}]
$array[] = array('Gender' => "female");
echo json_encode($array)."</br>";
//outputs :[{"title":"happy"},{"Gender":null}]

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

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

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