php, json to specific string - php

By POST I get this JSON (can have more than 3 values in it)
{"preferences":["Theater","Opera","Danse"]}
Well, I need to get
array('Theater', 'Opera', 'Degustation')
json_decode doesn't work.
Do you have any ideas please?
Thank you by advance

Try adding the true parameter:
$jsonData = '{"preferences":["Theater","Opera","Danse"]}';
$arrayData = json_decode($jsonData, true );
var_dump($arrayData['preferences']);
The last line outputs the following:
array(3) {
[0]=>
string(7) "Theater"
[1]=>
string(5) "Opera"
[2]=>
string(5) "Danse"
}
Which is what you want. Good luck!

That JSON string is wrapped in an object (denoted by curly braces {}). json_decode will give you the wrapper object whose "preferences" property is the array you're looking for.
$wrapper = json_decode($json_string);
$array = $wrapper->preferences;
json_decode might also be unavailable if you're using and older version of php. In that case you should try a php json library.

You might have used the output of the json_decode() function as an associated array while you hadn't have told the function to provide an associated array for you, or vice versa!! However, the following will get you the array at the preferences index:
<?php
$decoded = json_decode('{"preferences":["Theater","Opera","Danse"]}', true); // <-- note the second parameter is true.
echo '<pre>';
print_r($decoded['preferences']); // output: Array ( [0] => Theater [1] => Opera [2] => Danse )
// ^^^^^^^^^^^^^^^^^^^^^^^
// Note the usage of the output of the function as an associated array :)
echo '</pre>';
?>

Related

Saving form values to an Object as attributes (Associative Array, PHP, PDO, lunk head)

I'm working on an AJAX CRUD and I cannot get the form values in the Assoc. array to save individually as object attributes for the MySQL query.
I am following enter link description here but instead of the mysqli I'm using PDO.
Not much of a php person and this is my first OOP use of PDO and JSON.
The vardump() shows the input text is there...
// get posted data
$data = json_decode(file_get_contents("php://input"), true);
// set event property values
$event=>mainTitle = $data->main-title;
$event->subTitle = $data->sub-title;
$event->eventUrl = $data->event-url;
And the dumps:
array(9) {
["main-title"]=>
string(15) "Test Main Title"
["sub-title"]=>
string(14) "Test Sub title"
["event-url"]=>
string(9) "Test URTL"
...
object(Event)#3 (11) {
["conn":"Event":private]=>
object(PDO)#2 (0) {
}
["table_name":"Event":private]=>
string(8) "tblEvent"
["mainTitle"]=>
int(0)
["subTitle"]=>
int(0)
["eventUrl"]=>
int(0)
...
try changing $event=>mainTitle to $event->mainTitle
You have passed a second argument to json_decode() what means you'd like to get an array instead of the object. So just work like with the array. Replace to $event->mainTitle = $data['main-title'];
I found the answer for part of my problem here: Handling-JSON-like-a-boss-in-PHP
json_decode() is able to return both an object or associative array.
//For an object:
$result = json_decode($string);
//For an Assoc. Array:
$result = json_decode($string, true);
What I struggled with is that the var_dump() returns almost exact result for the two. They indeed have to be the same type.
The second part of my problem that was more subvert was having hyphens in the object attribute names. I didn't find a reason why but for sake of clarity in my code I just removed them.

Reading JSON file in PHP

I tried this code
$jsonlogcontents='{"buildings":"townhall","Army":{ "Paladins":{ "325648":0, "546545":4 }, "Knights":{ "325648":-2, "546545":0 } } }';
$phpArray = json_decode($jsonlogcontents, false);
echo $phpArray->buildings;
echo $phpArray->Army;
This is just a sample of my code, the JSON file is too large to include and has sensitive information. The problem I'm having is I can't get the value or print the value of
$phpArray->Army
It give's me an error. I can however print or get the value of
$phpArray->buildings
I'm thinking that when you decode a JSON file/contents in PHP, you can't get/print/store the value of a 'key' that has more set of info (more { and }) or brackets in it. You can only print/get values for keys who's value's contain only 1 value and nothing else.
If this is the case, what can I do to get the contents of the key that has more JSON codes in it. Also, how can I convert the contents of a key that has more JSON info in it into a string? the conversion is so I can display the value of that key to the page or echo it
The error is because Army is an object, and echo doesn't know how to convert it to a string for display. Use:
print_r($phpArray->Army);
or:
var_dump($phpArray->Army);
to see its contents.
P.S. $phpArray not an array but an object.
For Army however, I will need to do another json_decode() for that.
You don't. json_decode() decodes the entire structure in one call, into one large object (or array). No matter how deeply nested the data is, you call json_decode() once and you're done. That's why Army is not a JSON string any more.
When you are adding false as the second parameter to the json_encode it will updating all array to the sdClass empty objects.In this way you can the main array as the object
<?php
$json = '{
"buildings": "townhall",
"Army": {
"Paladins": {
"325648": 0,
"546545": 4
},
"Knights": {
"325648": -2,
"546545": 0
}
}
}';
$array = json_decode($json, true);
$object = (object)$array;
var_dump($object->Army);
?>
OUTPUT
array(2) {
["Paladins"]=>
array(2) {
[325648]=>
int(0)
[546545]=>
int(4)
}
["Knights"]=>
array(2) {
[325648]=>
int(-2)
[546545]=>
int(0)
}
}
Working Demo
It's because the output from your json_decode looks like this:
object(stdClass)(
'buildings' => 'townhall',
'Army' => object(stdClass)(
'Paladins' => object(stdClass)(
325648 => 0,
546545 => 4
),
'Knights' => object(stdClass)(
325648 => -2,
546545 => 0
)
)
)
Army is a standard object so it can't know how to echo it. You can however var_dump it:
var_dump($phpArray->Army);
The easiest solution is to treat it as a normal array with:
$phpArray = json_decode($jsonlogcontents, true);

read json output in php

how to read below json data in php?
i have "$json = json_decode($data,true); and
i tryied "$json->{'screenShareCode'};" but is is giving me an error? :(
array(5) {
["screenShareCode"]=>
string(9) "887874819"
["appletHtml"]=>
string(668) ""
["presenterParams"]=>
string(396) "aUsEdyygd6Yi5SqaJss0="
["viewerUrl"]=>
string(65) "http://api.screenleap.com/v2/viewer/814222219?accountid=myid"
["origin"]=>
string(3) "API"
}
The output you are showing is not json. It seems to be a print_r'ed array.
See http://json.org/example
Your output is regular array not JSON, so you access it as regular PHP array:
$x = $array['screenShareCode']
You are looking for json_encode (http://de2.php.net/json_encode)
What you posted is an array, not an object. Because you passed json_decode a second parameter of true, it responded with an associative array instead of an object.
To access a property of an associative array, you can do something like $json['screenShareCode'].

Cleaner way to echo multi dimension array

echo "{$line['text_1']}";
the above echo works fine ,however when it comes to 2d array, in my sublime, only {$line['text_2']} this part work fine. output error both sublime and browser
echo "$array_2d[{$line['text_1']}][{$line['text_2']}]";
any idea?
update
echo "$array_2d[$line['text_1']][$line['text_2']]";
using xampp, error Parse error: syntax error, unexpected '[', expecting ']' in C:\xampp\htdocs
and I'm just outputting a value from the mysql_fetch_assoc. I can do it in another way by echo '' however I'm trying to make my code easier for future editting and code copy paste
and yes I'm doing things like
echo "The price is $array_2d[$line['text_1']][$line['text_2']]"
with lots of html code in the double quote.
Why are you trying to output the array?
if it is for debugging purposes, you can just use the native php functions print_r() or var_dump()
You should be able to say
echo "item is {$array_2d[$line['text1']][$line['text2']]}";
to get to a subelement.
Of course, this is only really useful when it's not the only thing in the string. If you're only echoing the one value, you don't need the quotes, and things get simpler.
echo $array_2d[$line['text1']][$line['text2']];
this should work :
echo $array_2d[$line['text_1']][$line['text_2']];
When echoing variables, you don't have to use the quotes:
echo $array_2d[$line['text_1']][$line['text_2']];
If you do need to output something with that string, the concatentation operator can help you:
echo "Array: " . echo $array_2d[$line['text_1']][$line['text_2']];
You can use print_r() to echo the array.
e.g.:
print_r($array);
Output will be:
Array ( [test] => 1 [test2] => 2 [multi] => Array ( [multi] => 1 [multi2] => 2 ) )
Also you can use this to make it more readable in a HTML context:
echo '<pre>';
print_r($array);
echo '</pre>';
Output will be:
Array
(
[test] => 1
[test2] => 2
[multi] => Array
(
[multi] => 1
[multi2] => 2
)
)
You can use print_r() or var_dump() to echo an array.
The print_r() displays information about a variable in a way that's readable by humans whereas the var_dump() function displays structured information about variables/expressions including its type and value.
$array = 'YOUR ARRAY';
echo "<pre>";
print_r($array);
echo "</pre>";
or
$array = 'YOUR ARRAY';
var_dump($array);
Example variations
I'm wondering why you would try using the $line array as a key to access data in $array_2d.
Anyway, try this:
echo($line['text_1'].'<br>');
this:
echo($array_2d['text_1']['text_2'].'<br>');
and finally this (based on your "the $line array provides the keys for the $array_2d" array example)
$key_a = $line['text_1'];
$key_b = $line['text_2'];
echo($array_2d[$key_a][$key_b].'<br>');
Which can also be written shorter like this:
echo($array_2d[$line['text_1']][$line['text_2']].'<br>');
Verifying/Dumping the array contents
To verify if your arrays hold the data you expect, do not use print_r. Do use var_dump instead as it will return more information you can use to check on any issues you think you might be having.
Example:
echo('<pre>');
var_dump($array_2d);
echo('</pre>');
Differences between var_dump and print_r
The var_dump function displays structured information of a variable (or expression), including its type and value. Arrays are explored recursively with values indented to show structure. var_dump also shows which array values and object properties are references.
print_r on the other hand displays information about a variable in a readable way and array values will be presented in a format that shows keys and elements. But you'll miss out on the details var_dump provides.
Example:
$array = array('test', 1, array('two', 'more'));
output of print_r:
Array
(
[0] => test
[1] => 1
[2] => Array
(
[0] => two
[1] => more
)
)
output of var_dump:
array(3) {
[0]=> string(4) "test"
[1]=> int(1)
[2]=> array(2)
{
[0]=> string(3) "two"
[1]=> string(4) "more"
}
}

Undefined offset while accessing array element which exists

I have an array and PHP and when I print it out I can see the values I need to access, but when I try accessing them by their key I am getting a PHP Notice. I printed the array with print_r:
Array
(
[207] => sdf
[210] => sdf
)
When I try to access the array using the index I get an undefined offset notice. Here is my code:
print_r($output);
echo $output[207]; // Undefined Offset
echo $output["207"]; // Undefined Offset
The $output array is the result of a call to array_diff_key and is input originally as JSON through an HTTP POST request.
array_keys gives me the following:
Array
(
[0] => 207
[1] => 210
)
In response to the comments:
var_dump(key($output)); outputs:
string(3) "207"
var_dump(isset($output[key($output)])); outputs:
bool(false)
See this section on converting an object to an array in the PHP Manual:
The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name.
When converting to an array from an object in PHP, integer array keys are stored internally as strings. When you access array elements in PHP or use an array normally, keys that contain valid integers will be converted to integers automatically. An integer stored internally as a string is an inaccessible key.
Note the difference:
$x = (array)json_decode('{"207":"test"}');
var_dump(key($x)); // string(3) "207"
var_dump($x);
// array(1) {
// ["207"]=>
// string(4) "test"
// }
$y['207'] = 'test';
var_dump(key($y)); // int(207)
var_dump($y);
// array(1) {
// [207]=>
// string(4) "test"
// }
print_r on both those arrays gives identical output, but with var_dump you can see the differences.
Here is some code that reproduces your exact problem:
$output = (array)json_decode('{"207":"sdf","210":"sdf"}');
print_r($output);
echo $output[207];
echo $output["207"];
And the simple fix is to pass in true to json_decode for the optional assoc argument, to specify that you want an array not an object:
$output = json_decode('{"207":"sdf","210":"sdf"}', true);
print_r($output);
echo $output[207];
echo $output["207"];
The problem arises when casting to array an object that has string keys that are valid integers.
If you have this object:
object(stdClass)#1 (2) {
["207"]=>
string(3) "sdf"
["210"]=>
string(3) "sdf"
}
and you cast it with
$array = (array)$object
you get this array
array(2) {
["207"]=>
string(3) "sdf"
["210"]=>
string(3) "sdf"
}
which has keys that can only be accessed by looping through them, since a direct access like $array["207"] will always be converted to $array[207], which does not exist.
Since you are getting an object like the one above from json_decode() applied to a string like
$json = '{"207":"sdf", "210":"sdf"}'
The best solution would be to avoid numeric keys in the first place. These are probably better modelled as numeric properties of an array of objects:
$json = '[{"numAttr":207, "strAttr":"sdf"}, {"numAttr":210, "strAttr":"sdf"}]'
This data structure has several advantages over the present one:
it better reflects the original data, as a collection of objects
which have a numeric property
it is readily extensible with other properties
it is more portable across different systems
(as you see, your current data structure is causing issues in PHP, but if you
should happen to use another language you may easily encounter
similar issues).
If a property → object map is needed, it can be quickly obtained, e.g., like this:
function getNumAttr($obj) { return $obj->numAttr; } // for backward compatibility
$arr = json_decode($json); // where $json = '[{"numAttr":...
$map = array_combine(array_map('getNumAttr', $arr), $arr);
The other solution would be to do as ascii-lime suggested: force json_decode() to output associative arrays instead of objects, by setting its second parameter to true:
$map = json_decode($json, true);
For your input data this produces directly
array(2) {
[207]=>
string(3) "sdf"
[210]=>
string(3) "sdf"
}
Note that the keys of the array are now integers instead of strings.
I would consider changing the JSON data structure a much cleaner solution, though, although I understand that it might not be possible to do so.
I've just found this bug which causes array elements to be inaccessible sometimes in PHP when the array is created by a call to unserialize.
Create a test PHP file containing (or run from the command line) the following script:
<?php
$a = unserialize('a:2:{s:2:"10";i:1;s:2:"01";i:2;}');
print $a['10']."\n";
$a['10'] = 3;
$a['01'] = 4;
print_r($a);
foreach ($a as $k => $v)
{
print 'KEY: ';
var_dump($k);
print 'VAL: ';
var_dump($v);
print "\n";
}
If you get errors you have a version of PHP with this bug in it and I recommend upgrading to PHP 5.3
Try
var_dump($output);
foreach ($output as $key => val) {
var_dump($key);
var_dump($val);
}
to learn more on what is happening.
What exact line/statement is throwing you a warning?
How did you print the array? I would suggest print_r($arrayName);
Next, you can print individual elements like: echo $arrayName[0];
Try use my approach:
class ObjectToArray {
public static function convert( $object ) {
if( !is_object( $object ) && !is_array( $object ) ) {
return $object;
}
if( is_object( $object ) ) {
$object = get_object_vars( $object );
}
return array_map( 'ObjectToArray::convert', $object );
}
}
$aNewArray = ObjectToArray::convert($oYourObject);
Just put error_reporting(0); in you method or at start of file. It will solved your issue.

Categories