How do I create an empty JSON array?
I tried $finalJSON["items"][0] = ''; but that gave me {"items":[""]}
I tried $finalJSON["items"][0] = null; but that gave me {"items":[null]}
What I actually want is {"items":[]}
How to achieve this?
Your code actually creates an array with already one element with key 0 and value '' (empty string) or null. Instead, use:
$finalJSON["items"] = array();
Try this:
$arr['items'] = array();
echo json_encode($arr);
You should set an empty array:
$finalJSON = [];
$finalJSON["items"] = [];
echo json_encode($finalJSON);
Output:
{"items":[]}
Example
Consider this example:
<?php
$items = [];
echo json_encode($items);
The output is: [].
That is the "most empty" array you can create and convert into a json encoding.
So if you want such an array as value inside an object as property item, then use an object:
<?php
class myObject {
public $items = [];
}
echo json_encode(new myObject);
The output is: {"items":[]}
$finalJSON["items"] = []; //short syntax
or
$finalJSON["items"] = array(); //old syntax
and to output:
echo json_encode($finalJSON);
This should work
<?php
$finalJSON["items"] = array();
echo json_encode($finalJSON);
?>
Related
I tried to replace a json value if the id from json1 same with json2 than replace the name in json1, here my json:
$json1 = '[{"categoryId":"10","name":"Technology"},{"categoryId":"10","name":"Blog"},{"categoryId":"11","name":"Programming"}]';
$json2 = '[{"categoryId":"10","name":"Tech"}]';
My expected result is:
$json1 = '[{"categoryId":"10","name":"Tech"},{"categoryId":"10","name":"Tech"},{"categoryId":"11","name":"Programming"}]';
I did with javascript so far:
json1.forEach(function(json1) {
if (json2.categoryId === json1.categoryId) {
json1.name = json2.name
}
});
but how to do it over php language?
This will help you I hope
// Your json data
$json1 = '[{"categoryId":"10","name":"Technology"},{"categoryId":"11","name":"Blog"},{"categoryId":"12","name":"Programming"}]';
$json2 = '[{"categoryId":"10","name":"Tech"}]';
// Turn json into an array
$array1 = json_decode($json1, true);
$array2 = json_decode($json2, true);
// Loop to json2 as array
foreach ($array2 as $value) {
$categoryId = $value['categoryId'];
// Check if the categoryId exist in array 1 and get the index key
$key = array_search($categoryId, array_column($array1, 'categoryId'));
// Check if the key exist ena check if it has a name to be changed
if (isset($array1[$key]) && isset($array1[$key]['name'])) {
// Set the new name
$array1[$key]['name'] = $value['name'];
}
}
// Turn the array back into json
$json1 = json_encode($array1);
Did your solution work in JS? It seems to me, that in the loop, you should be comparing with the first entry of the json2 variable, as the whole json2 is a list of objects and does not itself have a name property.
In PHP, this could work like this:
$arr1 = json_decode($json1);
$arr2 = json_decode($json2);
$arr2entry = $arr2[0]; # this is what we want to compare against
foreach ($arr1 as &$arr1entry) { #[1]
if ($arr2entry["categoryId"] == $arr1entry["categoryId"]) {
$arr1entry["name"] = $arr2entry["name"];
}
}
#[1] notice the ampersand here, that's a reference assignment,
#it is needed to actually modify the content of the original array.
I have a PHP code that converts a JSON into an array of two elements.
{"object":"card","id":"card_1"}
But when I try to print the both, the first returns the value and the second only the boolean.
echo 'id = ' . $response["id"];
echo 'object = ' .$response["object"];
Getting this:
id = true
object = card
What is wrong?
It seems, that you use json_decode to convert your JSON data to an array. Use next basic example to get your expected data:
<?php
// Input
$json = '{"object":"card","id":"card_1"}';
$array = json_decode($json, true);
// Specific items
echo 'id = '.$array["id"].'<br>';
echo 'object = '.$array["object"].'<br>';
// All items
foreach($array as $key => $value) {
echo $key.": ".$value."<br>";
}
?>
Could you please provide the code you use to convert this JSON into an array ?
This works fine:
$jsonObject = '{"object":"card","id":"card_1"}';
$decodedObject = json_decode($jsonObject);
$object = $decodedObject->object;
$id = $decodedObject->id;
echo "Object: {$object}, ID: {$id}";
i want return my data from mysql to json array with do while loop.
when i return one record with json it is well. but i want return list of array in one json array.
how can do that with index in while? my code have error and i don't know how can do it. with one record it is well but more can't.
$json="array(";
do{
$json=."'$row_query['id']'=>array('fname'=>$row_query['fname'],'lname'=>$row_query['lname']),";
} while ($row_query = mysqli_fetch_assoc($query));
json=.")";
echo json_encode($json,JSON_UNESCAPED_UNICODE);
There's no need to add quotes, brackets, parentheses or whatever. json_encode function will do it for you. Just provide an array to it:
$json = [];
while ($row_query = mysqli_fetch_assoc($query)) {
$json[$row_query['id']] = [
'fname'=>$row_query['fname'],
'lname'=>$row_query['lname'],
];
}
echo json_encode($json,JSON_UNESCAPED_UNICODE);
This is the most super easy version. You may try this.
$json = new array();
do{
array_push($json,$row_query);
} while ($row_query = mysqli_fetch_assoc($query));
or
$json = [];
do{
$json[] = $row_query;
} while ($row_query = mysqli_fetch_assoc($query));
Atlast encode your json variable.
$json = json_encode($json);
echo $json;
Array : [{"ID":1},{"ID":2}]
$id=1;
I want to check if $id exists in the array.
Thank you!
You may try Laravel's Collection::contains method, for example:
$collection = collect(json_decode($jsonString, true));
if ($collection->contains(1) {
// Exists...
}
Also, you may use key/value pair like this:
if ($collection->contains('ID', 1) {
//...
}
Also, if you want to get that item from the collection then you may try where like this:
$id = $collection->where('ID', 1)->first(); // ['ID' => 1]
You have a json formatted array and you need to decode it using json_decode first. After that loop the array to check for the id that you want.
So the code should look like this:
$json = '[{"ID":1},{"ID":2}]';
$id = 1;
$data = json_decode($json, true);
foreach($data as $item){
if($item['id'] == $id) {
echo 'it exists';
}
}
Iterate the array using for loop and use the value as a param to json_decode.
$id = 1;
$arr = array('{"ID":1}', '{"ID":2}');
foreach($arr as $val) {
if (in_array($id, json_decode($val, TRUE))) {
echo "id present";
}
}
Try this, if value is exist it will give key of array
$jsondata = '[{"ID":1},{"ID":2}]';
$array = json_decode($jsondata,true);
$key = array_search(1, array_column($array, 'ID'));
Just check if the string is in the json array, with little computation.
I think it's the more efficient way. Check the result here.
<?php
$id = 1;
$array = ['{"ID":1}', '{"ID":2}'];
echo in_array(json_encode(["ID" => $id]), $array) ? 'Yes' : 'No';
I have a variable like this
$profile = $adapter->getProfile();
Now i'm using it like this
$profile->profileurl
$profile->websiteurl
$profile->etc
Now i want to use it in a foreach loop
So i created an array like this
$data = array('profileurl','websiteurl','etc');
foreach ($data as $d ) {
${$d} = ${'profile->'.$d};
}
When I use var_dump(${$d}) I see only NULL instead of values.
Whats wrong?
The following code:
${'profile->'.$d}
Should be changed to:
$profile->{$d};
This will create the variables as expected:
$profile = new stdClass();
$profile->profileurl = "test profileurl";
$profile->websiteurl = "test websiteurl";
$data = array('profileurl', 'websiteurl');
foreach ($data as $d) {
${$d} = $profile->{$d};
}
var_dump($profileurl, $websiteurl);
// string(15) "test profileurl"
// string(15) "test websiteurl"
My guess is that $profile = $adapter->getProfile(); returns an object. And you have fetched data using mysql_fetch_object() so the resulting $profile is an object
When you add the properties in an array you will have to do something like this
$data = array($profile->profileurl, $profile->websiteurl, $profile->etc);
Which will kill the entire idea of doing so. So i'd suggest better try modifying the $adapter->getProfile() method to return an array using mysql_fetch_assoc() which which will return and array and you can iterate it using
foreach($profile as $key => $value){
//whatever you want to do
echo $key . " : " . $value . "<br/>";
}
I don't know exactly why are you approaching foreach. My assumption is, you need
variable like
$profileurl = "something1", $websiteurl="something2" and more.
$profile = $adapter->getProfile();
Now just convert $profile object into Array as follows,
$profileArray = (array)$profile
Then use extract function,
extract($profileArray);
Now you get values in variable as
$profileurl = "something1";
$websiteurl="something2"
Then you can use those as normal php variable.