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.
Related
On the client side to comply with a whole bunch of complicated legacy code, I need JSON to look like this:
A. {"book":[{"title":"War and Peace.","author":"Leo Tolstoy"}]}
where the "value" side of the Dictionary is an array containing a dictionary e.g. [{}].
However, when retrieving a random item, my server code is outputting the following:
B. {"book":{"title":"War and Peace","author":"Leo Tolstoy"}}
where the "value" side is just a dictionary e.g. {}.
How can I generate the JSON so it looks like A instead of B?
Here is what is currently happening on the server to generate B:
The data is actually stored in JSON as:
$str = '[{"title":"War and Peace","author":"Leo Tolstoy"}]';
The code that outputs a random item is:
$array = json_decode($str, true);
$rand = $array[array_rand($array)];
echo json_encode(array('book'=>$rand));
How can I put the dictionary on the value side inside square brackets e.g. [{}]?
simply wrap you $rand variable inside bracket []. Curious to know What is the purpose of array_rand() here?
<?php
$str = '[{"title":"War and Peace","author":"Leo Tolstoy"}]';
$array = json_decode($str, true);
$rand = $array[array_rand($array)];
echo json_encode(array('book'=>[$rand]));
?>
DEMO: https://3v4l.org/dZJRn
I"m creating a PHP script that handles JSON input (via a $_POST variable). It"s extracts data from the JSON and uploads it to an SQL database. I want the JSON in a particular format:
$object = json_decode('{
"key_a":[{"value_a":10,"value_b":7},{"value_a":10,"value_b":7},{"value_a":10,"value_b":7}],
"key_b":[{"value_a":10,"value_b":7}],
"key_c":[{"value_a":10,"value_b":7},{"value_a":10,"value_b":7}]
}',true);
Basically, an object with keys in, each of which should hold an array (no matter what size it is). I use json_decode(json,true) to convert it to an associative array (as opposed to object). I"ve had to add lots of checks in for each of the keys, checking if they"re objects or arrays (as the ASP.net page that the extract comes from converts arrays with single objects in, to objects - removing the array that holds them). The checks then convert them back to arrays, if there"s an object where I"d like an array holding an object:
if(is_object($object["key_b"]))
{
$a = array();
$a[] = $object["key"];
$object["key"] = $a;
}
I then iterate through the array, adding the values to rows in an SQL database. This all works fine, but when converting back to JSON with json_encode, any keys that hold arrays with only one object in, remove the array, and leave just the object under that key:
echo(json_encode($object));
// RETURNED JSON
'{
"key_a":[{"value_a":10,"value_b":7},{"value_a":10,"value_b":7},{"value_a":10,"value_b":7}],
"key_b":{"value_a":10,"value_b":7},
"key_c":[{"value_a":10,"value_b":7},{"value_a":10,"value_b":7}]
}'
You see, key_b no longer holds an array, but an object! This is really annoying, as I plan to create a JavaScript script that iterates through the arrays, adding one DOM element (div) for each of the objects.
Why does this happen? Is there any way to keep them as arrays, even if there"s only one object in the array?
I"ve tried:
if(is_object($object["key_b"]))
{
$a = array();
$a[] = array_values($object["key"]);
$object["key"] = $a;
}
and
if(is_object($object["key_b"]))
{
$a = array();
$a[0] = array_values($object["key"]);
$object["key"] = $a;
}
But it seems like nothing prevents json_encode from affecting the JSON in this way.
It"s not hard to get around this - but it means adding one check per key (checking whether it"s an array or value), which is particularly time consuming as the data extract that comes through is really big.
Any advice would be greatly appreciated.
EDIT: changed ' to " in JSON - though, this is only an example I just wrote to show the structure.
EDIT: I'm using references to cut my coding time down, if this changes anything?:
$t =& $object["key_b"];
if(is_object($t))
{
$a = array();
$a[] = $t;
$t = $a;
}
It appears using is_object() on a key of an associative array will not return true. I just knocked up this example, to prove this:
$json = json_decode('{"job_details":{"a":[{"x":5},{"y":23},{"z":18}],"b":{"x":19},"c":[{"x":64},{"y":132}]}}',true);
echo(json_encode($json)."<br><br>");
$t =& $json["job_details"]["b"];
if(is_object($t))
{
$a = array();
$a[] = $t;
$t = $a;
echo("IS OBJECT<br><br>");
}
echo(json_encode($json));
I will find another means of checking what value is held within an associative arrays key.
I was actually trying to find whether the value in the key is an associative array or not (not an object) - I just didn't realise they were different in PHP.
I must just use this custom function:
function is_assoc($array)
{
return (bool)count(array_filter(array_keys($array), 'is_string'));
}
From: How to check if PHP array is associative or sequential?
Which returns true if the value is an associative array.
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.
{"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.
I'm not 100% but this ($settings) would be called an array in php:
$setting;
$setting['host'] = "localhost";
$setting['name'] = "hello";
but what's the name for this that's different to the above:
$settings = array("localhost", "hello");
Also from the first example how can i remove the element called name?
(please also correct my terminology if I have made a mistake)
I'm not 100% but this ($settings)
would be called an array in php:
You should be 100% sure, they are :)
but what's the name for this that's
different to the above:
This:
$setting['host'] = "localhost";
$setting['name'] = "hello";
And this are different ways of declaring a php array.
$settings = array("localhost", "hello");
In fact this is how later should be to match the first one with keys:
$settings = array("host" => "localhost", "name" => "hello");
Also from the first example how can i
remove the element called name?
You can remove with unset:
unset($setting['name']);
Note that when declaring PHP array, do:
$setting = array();
Rather than:
$setting;
Note also that you can append info to arrays at the end by suffixing them with [], for example to add third element to the array, you could simply do:
$setting[] = 'Third Item';
More Information:
http://php.net/manual/en/language.types.array.php
As sAc said, they are both array. The correct way to declare an array is $settings = array(); (as opposed to just $settings; in your first line.)
The main difference between the first and second way is that the first allows you to use $settings['host'] and $settings['name'], whereas the latter can only be used with numeric indices ($settings[0] and $settings[1]). If you want to use the first way, you can also declare your array like this: $settings = array('host'=>'localhost', 'name'=>'hello');
More reading on PHP arrays
Well this is indeed an array. You have different types of array's in php. The first example you mention is called an Associative Array. Simply an array with a string as a key.
An associative array can be declared in two ways:
1) (the way you declared it):
$sample = array();
$sample["name"] = "test";
2)
$sample = array("name" => "localhost");
Furthermore the first example can also be used to add existing items to an array. For example:
$sample["name"][] = "some_name";
$sample["name"][] = "some_other_name";
When you execute the above code with print_r($sample) you get something like:
Array ( [name] => Array ( [0] => some_name [1] => some_other_name ) )
Which is very usefull when adding multiple strings to an existing array.
Removing a value from an array is very simple,
Like mentioned above, use the unset function.
unset($sample["name"])
to unset the whole name value and values connected to it
Or when you only want to unset a specific item within $sample["name"] :
unset($sample["name"][0]);
or, ofcourse any item you'd like.
So basicly.. the difference between your first example and the latter is that the first is an associative array, and the second is not.
For further reference on arrays, visit the PHP manual on arrays