0

how do I assign a field of a json_encoded result to a variable. I have the following:

$jsonres = json_encode($result); //where result is an array holding fields including name (string), properties (object type or array)

I tried the following:

echo $jsonres['properties']; // failed with "Illegal string offset 'properties'"
var_dump ($jsonres->properties); //"Notice: Trying to get property of non-object in..." 

I need to be able to use the value of 'properties' in my form.

Thanks

Kingsley
  • 183
  • 1
  • 15
  • In your example $jsonres is an object. Whereas `$jsonres['properties']` access element of array. You have to use object notation (o->prop). – hindmost Feb 10 '14 at 11:52
  • @hindmost, sorry I don't get (o->prop). seems similar to what i put on var_dump ($jsonres->properties); right? – Kingsley Feb 10 '14 at 11:55
  • Where is definition of `Response` class you using? – hindmost Feb 10 '14 at 11:57
  • ok, pls assume I use: $jsonres = json_encode($result); I'll edit the question to avoid confussion or response – Kingsley Feb 10 '14 at 11:59
  • Result of `json_encode` is intended for use in Javascript, not in PHP. Obviously you have to use `json_decode` instead. Also if you want to use object notation you should pass 2nd argument of `json_decode` – hindmost Feb 10 '14 at 12:02
  • the problem is i need the value of a field in json encoded format. is there a way to allocate this field to a variable? for instance $j=$jsonres['properties'] //fails – Kingsley Feb 10 '14 at 12:06
  • I don't quite understand your problem. Why you want to use json in PHP? – hindmost Feb 10 '14 at 12:12
  • You want `properties` from the `$result` encoded in JSON right? – Neil Lunn Feb 10 '14 at 12:14
  • Provide value of `$result` variable. – hindmost Feb 10 '14 at 12:18
  • @NeilLunn Yes I want properties from $result encoded in JSON. – Kingsley Feb 10 '14 at 12:23
  • 1
    @Kingsley You're very hard to understand. So I guess you have to: 1) decode $result to php array (or object); 2) retrieve needed property; 3) encode it to JSON. – hindmost Feb 10 '14 at 12:29
  • Thanks @hindmost, you just gave me the logic to use. That's great :) – Kingsley Feb 10 '14 at 12:35
  • @hindmost, either post an answer of your own for Kingsley to accept, or Kingsley, accept my answer. You shouldn't leave a question unresolved. – NobleUplift Feb 10 '14 at 18:08
  • 1
    @NobleUplift I can't suggest a solution since I still don't understand the problem. I've requested the details, but OP didn't provided it. – hindmost Feb 10 '14 at 18:14

1 Answers1

1

Simply encode the properties property, not the entire object:

$jsonres = json_encode($result['properties']);
echo $jsonres;
NobleUplift
  • 5,631
  • 8
  • 45
  • 87