Push a value inside an array in a json in PHP [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a json like this {"1":["3","5","6","2","4","1"],"2":[]} and I want to push a value inside the array in the key "2" so I want to do like this {"1":["3","5","6","2","4","1"],"2":["myvalue"]}.
I've tried many ways but no luck.
This is what I tried
/// json = {"1":["3","5","6","2","4","1"],"2":[]}
$arrayparole= $json["2"];
array_push($arrayparole,"myvalue");
$json = $json + array("2"=>$arrayparole);
$record = json_encode($json);
but doesn't work.
Can you help me?

The JSON you have is basically a string. Therefore you cannot access the JSON using the index like you did.
What you need to do is to convert the JSON string into Array first. After you have the array, only you are able to access the values using index/keys.
You can only push value into an array.
You cannot append array to a string like you did.
$json = $json + array("2"=>$arrayparole);
Following are example of converting the string into array and use array_push to insert new value.
$jsonstring = '{"1":["3","5","6","2","4","1"],"2":[]}';
// decode the JSON string into Array
$array = json_decode($jsonstring, true);
// once you have the array, you can now push your value
array_push($array[2],"myvalue");
// now you can convert back the array to json
echo json_encode($array);

Related

Combine 2 or more JSON in PHP [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
My current JSON value is like this:
{"vegetable_names":["vegetables 1","vegetables 2","vegetables 3"]}{"grade":["XXL","A","B","S"]}{"packages":["Carton Boxes","Baskets"]}
But I would like to want the output to be like this:
{"vegetable_names":["vegetables 1","vegetables 2","vegetables 3"],"grade":["XXL","A","B","S"],"packages":["Carton Boxes","Baskets"]}
JSON is just a text representation of some data structure. Restore the data structure from the JSON strings, use PHP to modify it (or create a new data structure if it's more appropriate), encode the updated/new data structure to JSON again.
It seems the "JSON" you posted as input is not a JSON at all. It is the concatenation of three JSON strings. It doesn't work this way!
// Input JSON strings
$json1 = '{"vegetable_names":["vegetables 1","vegetables 2","vegetables 3"]}';
$json2 = '{"grade":["XXL","A","B","S"]}';
$json3 = '{"packages":["Carton Boxes","Baskets"]}';
// Restore the data structures as arrays
$data1 = json_decode($json1, TRUE);
$data2 = json_decode($json2, TRUE);
$data3 = json_decode($json3, TRUE);
// Combine them; it seems all you need is a simple merging
$data = array_merge($data1, $data2, $data3);
// Encode the combined arrays as JSON again
$output = json_encode($data);
I guess you get the Json like you described. If not I suggest you follow Paul Crovella's solution in making it right from the start.
So presumed that is no option for you, how about decoding the Json to an object or array merging those two or more and then encode them again as Json.
Ugly , but if the Json is created by a source independent from you, you can do it like that.

Extract data from nested json [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a MySQL database with a 'params' field containing Json encoded data. An example of the field contents is:
{"subcustom":{"slaveusers":["Jon Doe"]}}
How can I extract the name "Jon Doe" using Php?
Use json_decode to transform your json string into an object, if you know what you are looking for, do
<?php
$json = '{"subcustom":{"slaveusers":["Jon Doe"]}} ';
$obj = json_decode($json);
print_r($obj->subcustom->slaveusers[0]) ; // Jon Doe
?>
if you don't know the structure of your json, use a print_r or vardump to check the content
To do this as array you add the 'true' flag to json_decode():
$json = '{"subcustom":{"slaveusers":["Jon Doe"]}} ';
$json_array = json_decode($json, true);
print_r($json_array); // Array ([subcustom] => Array ([slaveusers] => Array ([0] => Jon Doe)))
Once you have an array you can follow the tree to get the element(s) you want:
echo $json_array['subcustom']['slaveusers'][0]; // Jon Doe

PHP: How to access Associative Array and solve "Array to String conversion notice"? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
EDIT: I found my mistake thanks to the comments about decoding the JSON data.
I am a total rookie in PHP and couldn't find a suitable method to access Associative array.
I have this JSON data:
[{"Id":"1"},{"Id":"2"},{"Id":"3"},{"Id":"4"},{"Id":"5"},{"Id":"6"},{"Id":"7"},{"Id":"8"}]
I need to fire another MySQLi query in my PHP code which requires 1,2,3... from above data.
Implementing various solutions on this site gives me Array to String Conversion error.
Please Help.
You can simply use array_column amd implode as
$json = '[{"Id":"1"},{"Id":"2"},{"Id":"3"},{"Id":"4"},{"Id":"5"},{"Id":"6"},{"Id":"7"},{"Id":"8"}]';
$data = implode(',',array_column(json_decode($json,true),'Id'));
echo $data;//1,2,3,4,5,6,7,8
Explanation:
json_decode($json,true) will convert your json string into an array
array_column(json_decode($json,true),'Id') will returns the values from a single column of the array, identified by the column_key i.e Id over here
implode will Join array elements with a glue string i.e ,.
convert json data to associative array:
<?php
$json = '[{"Id":"1"},{"Id":"2"},{"Id":"3"},{"Id":"4"},{"Id":"5"},{"Id":"6"},{"Id":"7"},{"Id":"8"}]';
$data = json_decode($json,true);
echo "<pre>";
print_r($data);
echo "<pre>";
?>

Insert a variable in blank array that variable contains array key and value [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
My variable which retrieve from database is:
$MyVariable="1=>'raju',2=>'rana',3=>'keya',4=>'muaz',5=>'',6=>'Asif'";
My array will be:
$MyArray=array($MyVariable);
Now I want to print a value using a key. Like:
echo $MyArray[2];
My output should be:
rana
But output is nothing!
eval() has security implications, but that's how this string of partial crap is turned into an actual array:
eval('$MyArray = array('.$MyVariable.');');
print_r($MyArray);
You should really store each value as a related row in another table instead of array data.
Your variable $myVariable is a string consisting of array keys.
If you were to write it as an array, it would work without problems:
$myvariable = array(
1 => 'raju',
2 => 'rana',
3 => 'keya'
// More entries
);
If this is the output of a function, you may want to make that function output JSON instead, as that is parseable to an array with just one json_decode call.
If you still want to parse this, you'll have to do some more advanced string parsing:
$data = array();
$bits = preg_match_callback("/(\d+)=>'(.*?)'(\,)?/", function($matches) use ($data){
$data[$matches[1]] = $matches[2];
}, $MyVariable);

JSON with PHP foreach [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Ok as per your suggestion I updated... By default Laravel returns JSON... I have set it to return an array but I am still getting the same row duplicated using:
$limits = array();
foreach($pieces as $coverage_limit){
$limits[] = coveragelimit::index($coverage_limit);
}
return json_encode($limits);
}
You're just overwriting $limits inside that foreach() loop. Perhaps you mean something more like
foreach($pieces as $coverage_limit){
$limits[] = coveragelimit::index($coverage_limit);
^^--- array push?
}
As well, you don't "implement" JSON instead of arrays. You work with NATIVE data structures, then encode that structure into JSON. JSON's a transport format, it's not something you should ever deal with natively.
the $limits array will hold the last value what coveragelimit::index() returns over the iterate, I would suggest a check on coveragelimit::index() return value if it falls with "Marc B"'s answer.
EDIT:
foreach($pieces as $key=>$coverage_limit) {
$limits[$key] = coveragelimit::index($coverage_limit);
}
or
foreach($pieces as $coverage_limit) {
array_push($limits, coveragelimit::index($coverage_limit));
}
both should returns the same as Marc B's answer

Categories