json_encode method in PHP - php

Hi I recently came across an example of json_encode function. Very confused about 1 part:
<?php
$runners=array{
'fname'=>5
'you' => 6
};
echo json_encode (array("runners"=>$runners));
?>
Question is, why can't the code on the last row simply be:
echo json_encode ($runners);
Thanks,

First of all, your array declaration is incorrect and you will get a syntax error if you run the code. You should use array(...) not array{...}. And the values need to be comma-separated. For example:
array(
key => value,
key2 => value2,
key3 => value3,
...
)
The following should work:
$runners = array(
'fname' => 5,
'you' => 6
);
echo json_encode($runners);
Output:
{"fname":5,"you":6}
How are these two different
The end result is different for both cases. When you do json_encode(array("runners"=>$runners));, the array is multi-dimensional, and the JSON output will change, too:
{"runners":{"fname":5,"you":6}}
Which one should you use
Depends. In the first array, you are simply creating two keys named fname and you, and in the second, you also add another key, runners, thereby making the array multi-dimensional. If you want that information to be present in the resulting JSON string, you should use the second one. If not, use the first one.

First you have use { in array it is not correct. and you have not have , between array elements.
you can use both. but you have to access 2 json by different ways. depending in your choice.
for first (it should be best choice) echo json_encode ($runners); you have one dimensional array.
$runners=array(
'fname'=>5,
'you' => 6
);
echo json_encode ($runners);
OUTPUT:
{"fname":5,"you":6}
In second you have 2d array.
$runners=array(
'fname'=>5,
'you' => 6
);
echo json_encode (array("runners"=>$runners));
OUTPUT:
{"runners":{"fname":5,"you":6}}
Live Demo : https://eval.in/92104

Firstly your array is wrogly used. It will use small brackets () not curly {}. So your array will become :
$runners=array(
'fname' => 5,
'you' => 6
);
Now when you do json_encode() as: echo json_encode ($runners); you will get the output:
{"fname":5,"you":6}
And if you do : echo json_encode (array("runners"=>$runners)); you will get output:
{"runners":{"fname":5,"you":6}}

Related

How can I parse/extract from a string in PHP? Specifically something between quotes

I have a string like this
{"2":{"name":"Moon Center","value":"moon7","value_raw":"moon7","id":2,"type":"select"},"3":{"name":"Multiple Choice","value":"Second Choice","value_raw":"Second Choice","id":3,"type":"radio"}}
How do I get for example, the content inside value to a variable? And I would want to be able to get it for every item with value in there. There will be several that come from a form in a single string.
This is the response from a form that stores the whole string in a string. Kinda wish it was an array but this is what i'm working with.
Your string is actually a JSON value. To get the data out of it, you must first json_decode it to an array (or object). If you choose an array, you can then use array_column to get all the 'value' values:
$json = '{"2":{"name":"Moon Center","value":"moon7","value_raw":"moon7","id":2,"type":"select"},"3":{"name":"Multiple Choice","value":"Second Choice","value_raw":"Second Choice","id":3,"type":"radio"}}';
$array = json_decode($json, true);
print_r(array_column($array, 'value'));
Output:
Array (
[0] => moon7
[1] => Second Choice
)
Demo on 3v4l.org

Get the value of a key in array

I have a variable and when I output it with print_r like this:
print_r($sort_order[$field->name]);
I get this:
Array ( [0] => Array ( [sort_order] => 92 ) )
but I only need the value which is 92. How can I do so it outputs only that when echoing it? example:
echo $sort_order[$field->name];
should output simple
92
Your $sortOrder array is actually an array of arrays, like:
[
[ 'sort_order' => 92 ]
]
That's why you can't print it like you expect.
Try:
echo $sort_order[0]['sort_order'];
Output:
92
The print_r() function is used to print human-readable information about a variable.
You can do both print and echo to output the required value:
echo $sort_order[$field->name];
print $sort_order[$field->name];
Hope this helps.
The command print_r displays the variable in a human readable way. So if you need to know all the info in a variable (in particular for large arrays), then you use that. For other use, e.g. when you only need to know the content (in I guess 99.999% of all the cases) you should either use echo as you already mentioned it or print (althoug, they are more or less the same).
Please consider this links for futher information
http://php.net/manual/en/function.print-r.php
What's the difference between echo, print, and print_r in PHP?

Php array_rand() printing variable name

I have an array that is filled with different sayings and am trying to output a random one of the sayings. My program prints out the random saying, but sometimes it prints out the variable name that is assigned to the saying instead of the actual saying and I am not sure why.
$foo=Array('saying1', 'saying2', 'saying3');
$foo['saying1'] = "Hello.";
$foo['saying2'] = "World.";
$foo['saying3'] = "Goodbye.";
echo $foo[array_rand($foo)];
So for example it will print World as it should, but other times it will print saying2. Not sure what I am doing wrong.
Drop the values at the start. Change the first line to just:
$foo = array();
What you did was put values 'saying1' and such in the array. You don't want those values in there. You can also drop the index values with:
$foo[] = 'Hello.';
$foo[] = 'World.';
That simplifies your work.
You declared your array in the wrong way on the first line.
If you want to use your array as an associative Array:
$foo=Array('saying1' => array (), 'saying2' => array(), 'saying3' => array());
Or you can go for the not associative style given by Kainaw.
Edit: Calling this on the not associative array:
echo("<pre>"); print_r($foo); echo("</pre>");
Has as output:
Array
(
[0] => saying1
[1] => saying2
[2] => saying3
[saying1] => Hello.
[saying2] => World.
[saying3] => Goodbye.
)
Building on what #Answers_Seeker has said, to get your code to work the way you expect it, you'd have to re-declare and initialise your array using one of the methods below:
$foo=array('saying1'=>'Hello.', 'saying2'=>'World.', 'saying3'=>'Goodbye.');
OR this:
$foo=array();
$foo['saying1'] = "Hello.";
$foo['saying2'] = "World.";
$foo['saying3'] = "Goodbye.";
Then, to print the contents randomly:
echo $foo[array_rand($foo)];

php: get array value without iterating through it?

hey guys,
i think i lost my mind.
print_r($location); lists some geodata.
array (
'geoplugin_city' => 'My City',
'geoplugin_region' => 'My Region',
'geoplugin_areaCode' => '0',
'geoplugin_dmaCode' => '0',
'geoplugin_countryCode' => 'XY',
'geopl ...
when I iterate through it with a foreach loop I can print each line.
However shouldn't it be possible to just get a specific value out of the array?
like print $location[g4]; should print the countryCode shouldn't it? Thank you!
echo $location['geoplugin_countryCode'];
Yes, you can get a specific value by key. The keys in your case are the geoplugin_ strings.
To get the country code:
// XY
$location['geoplugin_countryCode'];
$location['geoplugin_countryCode'];
would access country code
Where does "g4" come from? Did you mean "4"?
If you had a normal numerically-indexed array then, yes, you could write $location[4]. However, you have an associative array, so write $location['geoplugin_countryCode'].
there you are using an associative array, it is an array with a user defined key:value pair (similar to dictionaries on Python and Hash Tables on C#)
You can access the elements just using the Key (in this case geoplugin_city or geoplugin_region)
Using the standard array syntax:
$arrayValue = $array[key]; //read
$array[key] = $newArrayValue; //write
For example:
$location['geoplugin_city']; or $location['geoplugin_region'];
If you are not familiarwith PHP arrays you can take a look here:
http://php.net/manual/en/language.types.array.php
For a better understanding on array manipulation with PHP take a look of:
http://www.php.net/manual/en/ref.array.php

How do I access a string-indexed element of a PHP array?

I have the following array (in php after executing print_r on the array object):
Array (
[#weight] => 0
[#value] => Some value.
)
Assuming the array object is $arr, how do I print out "value". The following does NOT work:
print $arr->value;
print $val ['value'] ;
print $val [value] ;
So... how do you do it? Any insight into WHY would be greatly appreciated! Thanks!
echo $arr['#value'];
The print_r() appears to be telling you that the array key is the string #value.
After quickly checking the docs, it looks like my comment was correct.
Try this code:
print $arr['#value'];
The reason is that the key to the array is not value, but #value.
You said your array contains this :
Array (
[#weight] => 0
[#value] => Some value.
)
So, what about using the keys given in print_r's output, like this :
echo $arr['#value'];
What print_r gives is the couples of keys/values your array contains ; and to access a value in an array, you use $your_array['the_key']
You might want to take a look at the PHP manual ; here's the page about arrays.
Going through the chapters about the basics of PHP might help you in the future :-)

Categories