How to add this data to array ? Json - php

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}]

Related

PHP Save string and variable to a array

How do I save the string below with the variables to a array? It doesnt seem to work..
$str[] = {'name':'$data['name']','y':$data['values'],'key':'$data['key']'},
$str_str = implode(' ', $str);
echo $str_str;
Thanks.
You should read about basic array and string handling in PHP. Something like this should work:
$str[] = [
'name' => $data['name'],
'y' => $data['values'],
'key' => $data['key']
];
Maybe the best way is just use $str[] = json_encode($data);
Are you trying to save a JSON string into an array?
$var[] saves a value to the first available numeric key in the array $var
The string you would like to save looks like a JSON string, if that's what you want you can do so by:
$var[] = json_encode($data)
If the data array contains the following:
Array
(
[name] => value name
[y] => value y
[key] => value key
)
JSON encoding this array will give you:
{"name":"value name","y":"value y","key":"value key"}

How do I modify this PHP code to return nested results

I want to get this as a single object because I work with a JObject on the frontend.
I got an array at the moment but I am unsure how i should modify it so it returns a single object instead.
This is the code:
$contacts = array();
while ($row = mysqli_fetch_array($stmt))
{
$contact = array("ID" => $row['ProduktID'],
"Name" => $row['ProduktNamn'],
"Number" => $row['ProduktPris']);
array_push($contacts, $contact);
}
echo json_encode($contacts, JSON_PRETTY_PRINT);
And the goal is for it to look something like this with "results" as well so I can reach the whole thing:
To wrap your array of contacts in an object with a single results property:
echo json_encode(array('results' => $contacts), JSON_PRETTY_PRINT);
You can use typecasting to convert an array to an object:
$object = (object) $array_name;
or manually convert it into an object
$object = object;
foreach($arr as $key => $value)
{
$object->$key = $value;
}
Like this? Keep in mind an object is different then an array and your question is rather confusing.
while ($row = mysqli_fetch_array($stmt)){
$contact[] = [
"ID" => $row['ProduktID'],
"Name" => $row['ProduktNamn'],
"Number" => $row['ProduktPris']
];
}
json_encode(['result' => $contact]); // Forget the JSON_PRETTY_PRINT.
Using this method [], it will use the first available numeric index starting with 0. This way you don't have to push an array.

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

json_encode children items?

How can I use php json_encode to produce the following from an array?
{"issue":{"project_id":"Test Project","subject":"Test Issue"}}
I've been trying for the last 40 mins but I can't get it working for the life of me.
The best I can do is:
$arr = array ("project_id"=>"Baas","subject"=>"Test Issue");
echo json_encode($arr); // {"project_id":"Baas","subject":"Test Issue"}
The problem is making "issue" parent. Any hint on how to accomplish this?
Thanks!
The output you want is essentially an associative array nested in another associative array. So, create that data structure, then encode it.
$child_arr = array("project_id" => "Baas", "subject" => "Test Issue");
$parent_arr = array("issue" => $child_arr);
echo json_encode($parent_arr);
Or, if we're in a one-liner mood today:
$arr = array("issue" => array("project_id" => "Baas", "subject" => "Test Issue"));
echo json_encode($arr);
$arr = array ("issue" => array("project_id"=>"Baas","subject"=>"Test Issue"));

Add 2 values to 1 key in a PHP array

I have a result set of data that I want to write to an array in php. Here is my sample data:
**Name** **Abbrev**
Mike M
Tom T
Jim J
Using that data, I want to create an array in php that is of the following:
1|Mike|M
2|Tom|T
3|Jim|j
I tried array_push($values, 'name', 'abbreviation') [pseudo code], which gave me the following:
1|Mike
2|M
3|Tom
4|T
5|Jim
6|J
I need to do a look up against this array to get the same key value, if I look up "Mike" or "M".
What is the best way to write my result set into an array as set above where name and abbreviation share the same key?
PHP's not my top language, but try these:
array_push($values, array("Mike", "M"))
array_push($values, array("Tom", "T"))
array_push($values, array("Jim", "J"))
$name1 = $values[1][0]
$abbrev1 = $values[1][1]
or:
array_push($values, array("name" => "Mike", "abbrev" => "M"))
array_push($values, array("name" => "Tom", "abbrev" => "T"))
array_push($values, array("name" => "Jim", "abbrev" => "J"))
$name1 = $values[1]["name"]
$abbrev1 = $values[1]["abbrev"]
The trick is to use a nested array to pair the names and abbreviations in each entry.
$person = array('name' => 'Mike', 'initial' => 'M');
array_push($people, $person);
That said, I'm not sure why you're storing the data separately. The initial can be fetched directly from the name via substr($name, 0, 1).
You will need to create a two dimensional array to store more than one value.
Each row in your result set is already an array, so it will need to be added to your variable as an array.
array_push($values, array('name', 'abbreviation'));
maybe you create a simple class for that as the abbreviation is redundant information in your case
class Person
{
public $name;
pulbic function __construct($name)
{
$this->name = (string)$name;
}
public function getAbbrev()
{
return substr($this->name, 0, 1);
}
public function __get($prop)
{
if ($prop == 'abbrev') {
return $this->getAbbrev();
}
}
}
$persons = array(
new Person('Mike'),
new Person('Tom'),
new Person('Jim')
);
foreach ($persons as $person) {
echo "$person->name ($person->abbrev.)<br/>";
}
You could use two separate arrays, maybe like:
$values_names = array();
$values_initials = array();
array_push($values_names, 'Mike');
array_push($values_initials, 'M');
array_push($values_names, 'Tom');
array_push($values_initials, 'T');
array_push($values_names, 'Jim');
array_push($values_initials, 'J');
So you use two arrays, one for each of the second and third columns using the values in the first one as keys for both arrays.
php arrays work like hash lookup tables, so in order to achieve the desired result, you can initialize 2 keys, one with the actual value and the other one with a reference pointing to the first. For instance you could do:
$a = array('m' => 'value');
$a['mike'] = &$a['m']; //notice the end to pass by reference
if you try:
$a = array('m' => 'value');
$a['mike'] = &$a['m'];
print_r($a);
$a['m'] = 'new_value';
print_r($a);
$a['mike'] = 'new_value_2';
print_r($a);
the output will be:
Array
(
[m] => value
[mike] => value
)
Array
(
[m] => new_value
[mike] => new_value
)
Array
(
[m] => new_value_2
[mike] => new_value_2
)
have to set the same value to both Mike and M for keys.

Categories