I'm having trouble finding out why is the following code not working.
I've a JSON answer from a remote server, containting the following data:
...., "UserId":{"50423":"Free Kkludkjta","54379":"Sjkllyu\u00e9lkj Nolla","67103":"Tswt\u00f3 BLLA","64469":"Uz\u00e1h G","46699":"RT\u00e1sdt UTSF","46873":"Tam\u00e1s XXXX"}, ...
(names are swapped, but since there are some special chars in the aswer I've kept those)
And I have the following code sniplet, which gives 'array index undefined for idx 64469':
$proj_schema = json_decode($proj_schema);
var_dump($proj_schema->UserId);
$avail_users = (array)$proj_schema->UserId;
var_dump($avail_users);
var_dump($avail_users[64469]);
The output is the following:
C:\wamp\www\j34\administrator\components\com_mycomponent\views\myview\view.html.php:113:
object(stdClass)[309]
public '50423' => string 'Name1' (length=14)
public '54379' => string 'Name2' (length=18)
public '67103' => string 'Name3' (length=12)
public '64469' => string 'Name4' (length=15)
public '46699' => string 'Name5' (length=11)
public '46873' => string 'Name6' (length=12)
C:\wamp\www\j34\administrator\components\com_mycomponent\views\myview\view.html.php:115:
array (size=6)
'50423' => string 'Name1' (length=14)
'54379' => string 'Name2' (length=18)
'67103' => string 'Name3' (length=12)
'64469' => string 'Name4' (length=15)
'46699' => string 'Name5' (length=11)
'46873' => string 'Name6' (length=12)
Notice: Undefined offset: 64469 in C:\wamp\www\j34\administrator\components\com_mycomponent\views\myview\view.html.php on line 116
If I walk through the array with foreach and write out the element based on 'if ($key == 64469)' it echos the name, but I cannot access the name by array key.
Results are same with PHP 5.6.32 (I know) and PHP 7.1.0. Result is the same if I put the id in "" or '';
What am I missing with the casting?
You are using the JSON as an object and not as an array. Therefore, the key does not exist, because it is a property.
Decode with true as 2nd argument to get an array instead of an object.
$proj_schema = json_decode($proj_schema, true);
Related
I have the following PHP array:
array (size=9)
'script_desc' => string 'Test Script' (length=21)
'script_date' => string 'May 11 2016 15:40:48' (length=20)
'log_date' => string 'May 12 2016 09:17:58' (length=20)
'name' => string 'test name' (length=2)
'type' => string 'location_status' (length=15)
'status' => boolean false
'test.server.1' =>
array (size=1)
'packages' =>
array (size=2)
'package1' =>
array (size=4)
'package_name' => string 'package1' (length=10)
'current_version' => string 'package1-1.4.26-r1' (length=20)
'latest_version' => string '1.4.26-r1' (length=9)
'package_status' => string '=' (length=1)
'package2' =>
array (size=4)
'package_name' => string 'package2' (length=14)
'current_version' => string 'package2-0.31.1-r1' (length=24)
'latest_version' => string '0.31.1-r2' (length=9)
'package_status' => string '<' (length=1)
'test.server.2' =>
array (size=1)
'packages' =>
array (size=2)
'package1' =>
array (size=4)
'package_name' => string 'package1' (length=16)
'current_version' => string 'package1-0.35.1-r0' (length=26)
'latest_version' => string '0.35.1-r0' (length=9)
'package_status' => string '=' (length=1)
'package3' =>
array (size=4)
'package_name' => string 'package3' (length=3)
'current_version' => string 'package3-5.3.2-r0' (length=33)
'latest_version' => string '5.3.2-r0' (length=8)
'package_status' => string '=' (length=1)
'_id' => float 5
Here's the code that I use to try to insert this array into my mongo database:
68 function add_history_record($location)
69 {
70 $m = new MongoClient("mongodb://10.1.1.1:27017");
71 $db = $m->mymongodb;
72 $collection = $db->mycollection;
73 $location['_id'] = getNextSequence("locationid");
74 $cursor = $collection->insert($location);
75 var_dump($cursor);
76 }
The error message I'm getting is this:
Fatal error: Uncaught exception 'MongoException' with message ''.' not
allowed in key: test.server.1' in
/var/www/html/mongotestapp/inventory.php on
line 74
What I've tried So Far:
To prove to myself that I can have keys with "." in it, I used robomongo to add the following document:
{
"_id" : ObjectId("573483ae3747106e60a087f9"),
"test.server.1.1" : 123
}
It saved the document in my collection no problems.
I'm not sure what I'm missing in my PHP code...
Any suggestions?
EDIT 1:
I've changed my code to include the following:
68 function add_playbook_history_record($location)
69 {
70 $m = new MongoClient("mongodb://10.1.1.1:27017");
71 $db = $m->phonesys;
72 $collection = $db->inventory;
73 $location['_id'] = getNextSequence("locationid");
74 printf($location['_id']);
75 echo "<pre>".json_encode($location)."</pre>";
76 $cursor = $collection->insert($location, array("w"=>1));
77
78 // $cursor = $collection->insert($location, array("w" => 0,"j"=>true));
79 }
I can see that the system is generating a legit location id.
I also took the json formatted output and tested in jsonlint to make sure it's properly formatted etc.
Lastly, I started playing with the write options. When I enable line 78, the system doesn't return any error messages, but the records are not added to the database. But when I set w=1, it fails with the same error message about the key.
I've been playing around with the different options and reading this: http://php.net/manual/en/mongo.writeconcerns.php
but if you have any tips I'm all ears.
I don't have any shards or other servers. Just one main mongodb server running right now.
Thanks.
You can not have a . in your key names as the error message tells you.
MongoDB accepts this directly, but you would not be able to query against these field names as in queries, the dot has a special meaning:
// document
{foo:{bar:"baz"}}}
// query
db.col.find( { 'foo.bar' : 'baz' } );
All official drivers guard against putting a . (and other chars) in key names, and hence the PHP driver correctly rejects this.
I am trying to use Openstreetmap and PHP to point to a place on a map.
As you can see below, I retrieve a JSON array, but PHP returns a NULL value.
Note that my $url is a valid JSON (you can check it here).
<?
$url = 'http://nominatim.openstreetmap.org/search/Piazza%20Duomo%20Trento?format=json&addressdetails=1&limit=1&polygon_svg=1';
$html = file_get_contents($url);
$jsonout = json_decode($html);
echo $jsonout[0];
?>
What am I doing wrong?
What am I doing wrong?
First of all, your openning tag is not correct :
<? ----> <?php
Then, you cannot echo an array like that. Use var_dump on your array to see the structure.
When I try your code with the corrections, I got this :
array (size=1)
0 =>
object(stdClass)[1]
public 'place_id' => string '8577656' (length=7)
public 'licence' => string 'Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright' (length=84)
public 'osm_type' => string 'node' (length=4)
public 'osm_id' => string '924463183' (length=9)
public 'boundingbox' =>
array (size=4)
0 => string '46.0675164' (length=10)
1 => string '46.0676164' (length=10)
2 => string '11.1217498' (length=10)
3 => string '11.1218498' (length=10)
public 'lat' => string '46.0675664' (length=10)
public 'lon' => string '11.1217998' (length=10)
public 'display_name' => string 'Piazza Duomo, Piazza del Duomo, centro storico Trento, Trento, TN, TAA, 38122, Italia' (length=85)
public 'class' => string 'highway' (length=7)
public 'type' => string 'bus_stop' (length=8)
public 'importance' => float 0.311
public 'icon' => string 'http://nominatim.openstreetmap.org/images/mapicons/transport_bus_stop2.p.20.png' (length=79)
public 'address' =>
object(stdClass)[2]
public 'bus_stop' => string 'Piazza Duomo' (length=12)
public 'pedestrian' => string 'Piazza del Duomo' (length=16)
public 'suburb' => string 'centro storico Trento' (length=21)
public 'city' => string 'Trento' (length=6)
public 'county' => string 'TN' (length=2)
public 'state' => string 'TAA' (length=3)
public 'postcode' => string '38122' (length=5)
public 'country' => string 'Italia' (length=6)
public 'country_code' => string 'it' (length=2)
public 'svg' => string 'cx="11.1217998" cy="-46.067566399999997"' (length=40)
In answer to your question, except for trying to output an array with the following statement
echo $jsonout[0];
Which will throw a Catchable fatal error: Object of class stdClass could not be converted to string
Everything is ok.
If this is about accessing the members of the json_decode return, see below
$jsonout is an array with one element,
that one element is an object, you can access its members like this
print $jsonout[0]->licence;
Which will output
Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright
If you'd like an associative array, you can pass the second argument for json_decode, like this
$jsonout = json_decode($html,true);
print $jsonout[0]['display_name'];
Which will decode the json into an associative array and will display in a similar way
Piazza Duomo, Piazza del Duomo, centro storico Trento, Trento, TN, TAA, 38122, Italia
please use print_r() in place of echo
$url = "http://nominatim.openstreetmap.org/search/Piazza%20Duomo%20Trento?format=json&addressdetails=1&limit=1&polygon_svg=1";
$html = file_get_contents($url);
$jsonout = json_decode($html);
print_r($jsonout[0]);
and you will get your result.
or you can print $jsonout[0]["license"]
If I do the following in this view composer:
View::composer('product.edit', function($view)
{
$viewdata = $view->getData();
dd($viewdata);
});
I can see in the output that exists 'language_id', however I don't know how to retrieve it, since $viewdata['language_id'] will throw an exception.
How should I go about this?
Update:
The accepted answer led me to discover that when a presenter is involved in this operation, the model will be available in the offset, here is the final code:
View::composer('product.edit', function($view)
{
$data = $view->offsetGet('product')->toArray();
echo $data['language_id'];
exit;
});
You may try this:
$language_id = $view->offsetGet('language_id');
Following public methods are available in the $view object (An instance of Illuminate\View\View)
0 => string '__construct' (length=11)
1 => string 'render' (length=6)
2 => string 'renderSections' (length=14)
3 => string 'with' (length=4)
4 => string 'nest' (length=4)
5 => string 'withErrors' (length=10)
6 => string 'getEnvironment' (length=14)
7 => string 'getEngine' (length=9)
8 => string 'getName' (length=7)
9 => string 'getData' (length=7)
10 => string 'getPath' (length=7)
11 => string 'setPath' (length=7)
12 => string 'offsetExists' (length=12)
13 => string 'offsetGet' (length=9)
14 => string 'offsetSet' (length=9)
15 => string 'offsetUnset' (length=11)
16 => string '__get' (length=5)
17 => string '__set' (length=5)
18 => string '__isset' (length=7)
19 => string '__unset' (length=7)
20 => string '__call' (length=6)
21 => string '__toString' (length=10)
You may also try something like this:
if($view->offsetExists('language_id')) {
$language_id = $view->offsetGet('language_id');
}
Worth noting you can also access view data using the attribute syntax (at least starting Laravel 8):
$languageId = $view->product->language_id ?? null;
I have a problem with JSON data in PHP. I need to use data from this JSON in my SQL statement. When I'm trying to debug it with echo(var_dump, or print_r is not working too) command the output with is
{"records":"tekst","name":"[object Object]"}
This is a JSON structre:
{
records: 'tekst',
name: {
imie: 'imie1',
nazwisko: 'nazwisko1'
}
}
I'm trying to decode this by json_decode(), but I have an error
"Warning: json_decode() expects parameter 1 to be string, array
given".
Does anyone know what's wrong?
PHP manual about JSON and the format required: function.json-decode. basically, double quotes only and names must be quoted.
a demonstration of conversion using PHP.
So, you supply the json string that looks like, with the whitespace removed, like this:
{records:[{id:1,name:'n1'},{id:2,name:'n2'}]}
Which is an object containing an array with two entries that could be arrays or objects.
Except, it is not a valid JSON string as it contains single quotes. And PHP wants all the names in double quotes, as in "id":1.
So, possible PHP code to recreate that, assuming arrays as the inner entries is:
$json = new stdClass();
$records = array();
$entry = array('id' => 1, 'name' => 'n1');
$records[] = $entry;
$entry = array('id' => 2, 'name' => 'n2');
$records[] = $entry;
$json->records = $records;
$jsonEncoded = json_encode($json);
Which, when 'dump'ed looks like:
object(stdClass)[1]
public 'records' =>
array
0 =>
array
'id' => int 1
'name' => string 'n1' (length=2)
1 =>
array
'id' => int 2
'name' => string 'n2' (length=2)
Now, the string that structure produces is:
{"records":[{"id":1,"name":"n1"},{"id":2,"name":"n2"}]}
Which looks similar to yours but is not quite the same. Note the names in double quotes.
However, if your json string looked the same then PHP could decode it, as is shown below:
$jsonDecoded = json_decode($jsonEncoded);
var_dump($jsonDecoded, 'decoded');
Output: Note all objects...
object(stdClass)[2]
public 'records' =>
array
0 =>
object(stdClass)[3]
public 'id' => int 1
public 'name' => string 'n1' (length=2)
1 =>
object(stdClass)[4]
public 'id' => int 2
public 'name' => string 'n2' (length=2)
We may want arrays instead so use the true as the second parameter in the 'decode'
$jsonDecoded = json_decode($jsonEncoded, true);
var_dump($jsonDecoded, 'decoded with true switch');
Output: with arrays rather than objects.
array
'records' =>
array
0 =>
array
'id' => int 1
'name' => string 'n1' (length=2)
1 =>
array
'id' => int 2
'name' => string 'n2' (length=2)
string 'decoded with true switch' (length=24)
I am trying to parse out certain things within the JSON code, but the problem is that the two groups of arrays that have the information in it I need have random names, here is from the var_dump:
array (size=2)
'results' =>
array (size=1)
0 => string 'Phone.5d5b6fef-a2e0-4b08-cfe3-bc7128b776c3.Durable' (length=50)
'dictionary' =>
array (size=3)
'Person.51f28c76-2993-42d3-8d65-4ea0a66c5e16.Ephemeral' =>
array (size=8)
'id' =>
array (size=5)
...
'type' => null
'names' =>
array (size=1)
...
'age_range' => null
'locations' => null
'phones' =>
array (size=1)
...
'best_name' => string 'John Smith' (length=15)
'best_location' => null
'Location.28dc9041-a0ee-4613-a3b0-65839aa461da.Durable' =>
array (size=30)
'id' =>
array (size=5)
...
'type' => string 'ZipPlus4' (length=8)
'valid_for' => null
'legal_entities_at' => null
'city' => string 'City' (length=8)
'postal_code' => string '12345' (length=5)
'zip4' => string '4812' (length=4)
'state_code' => string 'MO' (length=2)
'country_code' => string 'US' (length=2)
'address' => string 'Main St, City, MO 12345-4812' (length=33)
'house' => null
No I am trying to get best_name from under the part that starts with Person and address under Location. But when I do:
$string = file_get_contents($url);
$json=json_decode($string,true);
var_dump($json);
echo $json['dictionary']['Person']['best_name'];
I get Undefined index: Person error, because the actual object name for Person is:
Person.51f28c76-2993-42d3-8d65-4ea0a66c5e16.Ephemeral which is different every time I do a search. Is there a way to do this without putting the random generated line in?
Hopefully this makes sense, thanks for the help in advance!
If the Person key always starts with the string "Person", than simply do a foreach and check the key which contains this string.
Like:
foreach ($json['dictionary'] as $key => $value) {
if (preg_match('/^Person/', $key)) {
echo $json['dictionary'][$key]['best_name'];
}
}
Of course this get complicated, if you have multiple keys which start with "Person".
You can do the same with "Location" or any other string you need.
How about something like this ... loop through $json['dictionary']'s index keys to find something that starts with "Person".
$foundIt = false;
foreach (array_keys($json['dictionary']) as $key) {
if (substr($key,0,6) == 'Person') {
$foundIt = $key;
break;
}
}
if ($foundIt) { echo $json['dictionary'][$foundIt]['best_name']; }