I have this code
$status = array(
"message"=>"error",
"club_id"=>$_club_id,
"status"=>"1",
"membership_info"=>array(),
);
echo json_encode($status);
This function return json:
{"message":"error","club_id":275,"status":"1","membership_info":[]}
But I need json like this:
{"message":"error","club_id":275,"status":"1","membership_info":{}}
use the JSON_FORCE_OBJECT option of json_encode:
json_encode($status, JSON_FORCE_OBJECT);
Documentation
JSON_FORCE_OBJECT (integer)
Outputs an object rather than an array when a non-associative array is used. Especially useful when the recipient of the output is expecting an object and the array is empty. Available since PHP 5.3.0.
Or, if you want to preserve your "other" arrays inside your object, don't use the previous answer, just use this:
$status = array(
"message"=>"error",
"club_id"=>$_club_id,
"status"=>"1",
"membership_info"=> new stdClass()
);
$status = array(
"message"=>"error",
"club_id"=>$_club_id,
"status"=>"1",
"membership_info"=>(object) array(),
);
By casting the array into an object, json_encode will always use braces instead of brackets for the value (even when empty).
This is useful when can't use JSON_FORCE_OBJECT and when you can't (or don't want) to use an actual object for the value.
There's no difference in PHP between an array and an "object" (in the JSON sense of the word). If you want to force all arrays to be encoded as JSON objects, set the JSON_FORCE_OBJECT flag, available since PHP 5.3. See http://php.net/json_encode. Note that this will apply to all arrays.
Alternatively you could actually use objects in your PHP code instead of arrays:
$data = new stdClass;
$data->foo = 'bar';
...
Maybe it's simpler to handle the edge case of empty arrays client-side.
I know this is an old question, but it's among the first hits on Google, so I thought I should share an alternative solution.
Rather than using standard PHP arrays, in PHP 7+ you can instead use Map() as part of the Data Structure extension. Documentation.
A Map object has practically identical performance as arrays and also implements ArrayAccess so it can be accessed as a regular array. Contrary to a standard array, however, it will always be associative and works as expected with json_encode. It also has some other minor benefits like object keys and better memory handling.
Some example usage:
use Ds\Map;
$status = new Map([
"message"=>"error",
"club_id"=>$_club_id,
"status"=>"1",
"membership_info"=>array(),
]);
$map = new Map();
print json_encode($map); // {}
$map = new Map();
$map["foo"] = "bar";
print json_encode($map); // {"foo":"bar"}
print $map["foo"]; // bar
$map = new Map();
$map[1] = "foo";
$map[2] = "bar";
$map[3] = "baz";
print json_encode($map); // {"1":"foo","2":"bar","3":"baz"}
While this may not be considered elegant, a simple string replace can effectively address this.
str_replace("[]", "{}", json_encode($data));
This mitigates the issue of JSON_FORCE_OBJECT converting a normal array into an object.
Related
I have this code
$status = array(
"message"=>"error",
"club_id"=>$_club_id,
"status"=>"1",
"membership_info"=>array(),
);
echo json_encode($status);
This function return json:
{"message":"error","club_id":275,"status":"1","membership_info":[]}
But I need json like this:
{"message":"error","club_id":275,"status":"1","membership_info":{}}
use the JSON_FORCE_OBJECT option of json_encode:
json_encode($status, JSON_FORCE_OBJECT);
Documentation
JSON_FORCE_OBJECT (integer)
Outputs an object rather than an array when a non-associative array is used. Especially useful when the recipient of the output is expecting an object and the array is empty. Available since PHP 5.3.0.
Or, if you want to preserve your "other" arrays inside your object, don't use the previous answer, just use this:
$status = array(
"message"=>"error",
"club_id"=>$_club_id,
"status"=>"1",
"membership_info"=> new stdClass()
);
$status = array(
"message"=>"error",
"club_id"=>$_club_id,
"status"=>"1",
"membership_info"=>(object) array(),
);
By casting the array into an object, json_encode will always use braces instead of brackets for the value (even when empty).
This is useful when can't use JSON_FORCE_OBJECT and when you can't (or don't want) to use an actual object for the value.
There's no difference in PHP between an array and an "object" (in the JSON sense of the word). If you want to force all arrays to be encoded as JSON objects, set the JSON_FORCE_OBJECT flag, available since PHP 5.3. See http://php.net/json_encode. Note that this will apply to all arrays.
Alternatively you could actually use objects in your PHP code instead of arrays:
$data = new stdClass;
$data->foo = 'bar';
...
Maybe it's simpler to handle the edge case of empty arrays client-side.
I know this is an old question, but it's among the first hits on Google, so I thought I should share an alternative solution.
Rather than using standard PHP arrays, in PHP 7+ you can instead use Map() as part of the Data Structure extension. Documentation.
A Map object has practically identical performance as arrays and also implements ArrayAccess so it can be accessed as a regular array. Contrary to a standard array, however, it will always be associative and works as expected with json_encode. It also has some other minor benefits like object keys and better memory handling.
Some example usage:
use Ds\Map;
$status = new Map([
"message"=>"error",
"club_id"=>$_club_id,
"status"=>"1",
"membership_info"=>array(),
]);
$map = new Map();
print json_encode($map); // {}
$map = new Map();
$map["foo"] = "bar";
print json_encode($map); // {"foo":"bar"}
print $map["foo"]; // bar
$map = new Map();
$map[1] = "foo";
$map[2] = "bar";
$map[3] = "baz";
print json_encode($map); // {"1":"foo","2":"bar","3":"baz"}
While this may not be considered elegant, a simple string replace can effectively address this.
str_replace("[]", "{}", json_encode($data));
This mitigates the issue of JSON_FORCE_OBJECT converting a normal array into an object.
Question is related with example from here http://lv1.php.net/array_merge
$beginning = 'foo';
$end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
Usually I use such code $result2 = array_merge( array($beginning), $end );
$end is already an array. Why need (array)$end....
Tested and see the same result.
So question. Is array_merge( array($beginning), $end ) correct code?
Seems now understood why it is reasonable to use (array)
For example $var2 = array('test2');
print_r( array($var2) );
would be multidimensional array
but
print_r( (array)$var2 );
would be the same array as initial.
There is a slight difference between array($foo) and (array)$foo, but it won't affect the output.
While array($foo) will try to build an array out of $foo, obviously returning an array, (array)$foo will try to look at$foo like it is an array, hence returning an array. Both have the exact same result if your variable is a good candidate for an array, but (array)$foo may have a stronger semantic aspect since it exposes your intention of using the variable as an array, rather than building an array out of it.
array_merge only accepts parameters of type array (Since PHP 5.0)
Convert all parameters use typecasting, therefore
Add (array) before the variable, it's means convert the data type into array, case it is not array.
Note:
If you can ensure all of the variables which used in array_merge ARE array. You can direct access it, instead of adding the (array).
Yes, it's correct code. If you are sure that the parameter is already an array you don't need the type casting.
Is it possible in php to change the name used to create an associative array? I am using mongo in php but it's getting confusing using array() in both cases of indexed arrays and associative arrays. I know you can do it in javascript by stealing the Array.prototype methods but can it be done in php my extending the native object? it would be much easier if it was array() and assoc() they would both create the same thing though.
EDIT -------
following Tristan's lead, I made this simple function to easily
write in json in php. It will even take on variable from within
your php as the whole thing is enclosed in quotes.
$one = 'newOne';
$json = "{
'$one': 1,
'two': 2
}";
// doesn't work as json_decode expects quotes.
print_r(json_decode($json));
// this does work as it replaces all the single quotes before
// using json decode.
print_r(jsonToArray($json));
function jsonToArray($str){
return json_decode(preg_replace('/\'/', '"', $str), true);
}
In PHP there is no "name used to create an associative array" or "name used to create an indexed array". PHP Arrays are ordered maps like in many other scripting languages.
This means that you can use an array whichever way you please.
If you wanted an indexed array..
$indexedArray = array();
$indexedArray[] = 4; // Append a value to the array.
echo $indexedArray[0]; // Access the value at the 0th index.
Or even..
$indexedArray = [0, 10, 12, 8];
echo $indexedArray[3]; // Outputs 8.
If you want to use non integer keys with your array, you simply specify them.
$assocArray = ['foo' => 'bar'];
echo $assocArray['foo']; // Outputs bar.
{"coord":{"lon":73.69,"lat":17.8},"sys":{"message":0.109,"country":"IN","sunrise":1393032482,"sunset":1393074559},"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01n"}],"base":"cmc stations","main":{"temp":293.999,"temp_min":293.999,"temp_max":293.999,"pressure":962.38,"sea_level":1025.86,"grnd_level":962.38,"humidity":78},"wind":{"speed":1.15,"deg":275.503},"clouds":{"all":0},"dt":1393077388,"id":1264491,"name":"Mahabaleshwar","cod":200}
I am trying to fetch description from the weather from the json above but getting errors in php. I have tried the below php code:
$jsonDecode = json_decode($contents, true);
$result=array();
foreach($jsonDecode as $data)
{
foreach($data{'weather'} as $data2)
{
echo $data2{'description'};
}
}
Any help is appreciated. I am new in using json.
You have to use square brackets ([]) for accessing array elements, not curly ones ({}).
Thus, your code should be changed to reflect these changes:
foreach($data['weather'] as $data2)
{
echo $data2['description'];
}
Also, your outer foreach loop will cause your code to do something completely different than you intend, you should just do this:
foreach($jsonDecode['weather'] as $data2)
{
echo $data2['description'];
}
Your $jsonDecode seems to be an array, so this should work-
foreach($jsonDecode['weather'] as $data)
{
echo $data['description'];
}
You can access data directly with scopes
$json = '{"coord":{"lon":73.69,"lat":17.8},"sys":{"message":0.109,"country":"IN","sunrise":1393032482,"sunset":1393074559},"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01n"}],"base":"cmc stations","main":{"temp":293.999,"temp_min":293.999,"temp_max":293.999,"pressure":962.38,"sea_level":1025.86,"grnd_level":962.38,"humidity":78},"wind":{"speed":1.15,"deg":275.503},"clouds":{"all":0},"dt":1393077388,"id":1264491,"name":"Mahabaleshwar","cod":200}';
$jsonDecode = json_decode($json, true);
echo $jsonDecode['weather'][0]['description'];
//output Sky is Clear
As you can see wheater` is surrounded with scopes so that means it is another array. You can loop throw that array if you have more than one result
foreach($jsonDecode['weather'] as $weather)
{
echo $weather['description'];
}
Live demo
If the result of decode is an array, use:
$data['weather']
If the result is an object, use:
$data->weather
you have to access "weather" with "[]" operator
like this,
$data["weather"]
There is several things worth answering in your question:
Q: What's the difference between json_decode($data) and json_decode($data, true)?
A: The former converts JSON object to a PHP object, the latter creates an associative array: http://uk1.php.net/json_decode
In either case, there is no point on iterating over the result. You probably want to access just the 'weather' field:
$o = json_decode($data) => use $weather = $o->weather
$a = json_decode($data, true) => use $weather = $a['weather']
Once you have the 'weather' field, look carefully what it is:
"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01n"}]
It's an array, containing a single object. That means you will either need to iterate over it, or use $clearSky = $weather[0]. In this case, it does not matter which approach of json_decode did you choose => JSON array is always decoded to a PHP (numeric indexed) array.
But, once you get $clearSky, you are accessing the object and it again matters, which approach you chose - use arrow or brackets, similarly to the first step.
So, the correct way to get for exaple the weather description would be either of these:
json_decode($data)->weather[0]->description
json_decode($data, true)['weather'][0]['description']
Note: In the latter case, dereferencing result of the function call is supported only in PHP 5.4 or newer. In PHP 5.3 or older, you have to create a variable.
Note: I also encourage you to always check if the expected fields are actually set in the result, using isset. Otherwise you will try to access undefined field, which raises an error.
In javascript you can easily create objects and Arrays like so:
var aObject = { foo:'bla', bar:2 };
var anArray = ['foo', 'bar', 2];
Are similar things possible in PHP?
I know that you can easily create an array using the array function, that hardly is more work then the javascript syntax, but is there a similar syntax for creating objects? Or should I just use associative arrays?
$anArray = array('foo', 'bar', 2);
$anObjectLikeAssociativeArray = array('foo'=>'bla',
'bar'=>2);
So to summarize:
Does PHP have javascript like object creation or should I just use associative arrays?
For simple objects, you can use the associative array syntax and casting to get an object:
<?php
$obj = (object)array('foo' => 'bar');
echo $obj->foo; // yields "bar"
But looking at that you can easily see how useless it is (you would just leave it as an associative array if your structure was that simple).
There was a proposal to implement this array syntax. But it was declined.
Update The shortened syntax for arrays has been rediscussed, accepted, and is now on the way be released with PHP 5.4.
But there still is no shorthand for objects. You will probably need to explicitly cast to object:
$obj = (object) ['foo'=>'bla', 'bar'=>2];
As of PHP 5.4, you can do this:
$array = ['foo'=>'bla', 'bar'=>2];
It's not much shorter, but you'll appreciate it if you need to use a lot of hard coded nested arrays (which isn't altogether uncommon).
If you want an object, you would still need to cast each array:
$object = (object) ['foo'=>'bla', 'bar'=>2];
According to the new PHP syntaxes,
You can use
$array = [1,2,3];
And for associative arrays
$array = ['name'=>'Sanket','age'=>22];
For objects you can typecast the array to object
$object = (object)['name'=>'Sanket','age'=>22];
There is no object shorthand in PHP, but you can use Javascript's exact syntax, provided you use the json_encode and json_decode functions.
The method provided by crescentfresh works very well but I had a problem appending more properties to the object. to get around this problem I implemented the spl ArrayObject.
class ObjectParameter extends ArrayObject {
public function __set($name, $value) {
$this->$name = $value;
}
public function __get($name) {
return $this[$name];
}
}
//creating a new Array object
$objParam = new ObjectParameter;
//adding properties
$objParam->strName = "foo";
//print name
printf($objParam->strName);
//add another property
$objParam->strUser = "bar";
There is a lot you can do with this approach to make it easy for you to create objects even from arrays, hope this helps .
Like the json_decode idea, wrote this:
function a($json) {
return json_decode($json, true); //turn true to false to use objets instead of associative arrays
}
//EXAMPLE
$cat = 'meow';
$array = a('{"value1":"Tester",
"value2":"'.$cat.'",
"value3":{"valueX":"Hi"}}');
print_r($array);