So this might be a simple question but not one I can find an answer for I have a variable that looks at a standard class object and stores the value from the various field names. Unfortunately, one of my fields is called [JOB::c_job_id]. If I use this in my variable
$jobid = ($json_data_single->response->data[0]->fieldData->JOB::c_job_id);
then it thinks the:: is a Scope Resolution Operator(::) but I just want to retrieve the data from the field, how can I do this?
Any help will be greatly appreciated.
If there is no way for you to rename that very unfortunately named key in the JSON, you can take one of the following approaches:
$json = '{"JOB::c_job_id": 453}';
$decodedAsObject = json_decode($json);
var_dump($decodedAsObject->{'JOB::c_job_id'});
$decodedAsArray = json_decode($json, true);
var_dump($decodedAsArray['JOB::c_job_id']);
The first one requires you to encase the property name in {} to make it be interpreted literally. The other is a bit more straightforward, because when you decode as an array, array keys are simple strings and there is no trouble when they contain characters or character sequences that can otherwise be interpreted as having special meaning for execution.
Live test available here.
Related
I am making a web app. In one part of it, I have JS send a string(in json format) to PHP.
The value php receives is:
{"date":"24-03-2014","Cars":["Cheap","Expensive"]}
Now, this is saved in a variable $meta. The problem I am facing is, as to how do I convert this string into an object and reference each individual entry separately.
I have tried json_decode and json_encode
and then I have referenced each variable using $meta.["date"] and $meta.date but nothing seams to work. I am getting just { as the output.
What's the correct way to do this?
$str = '{"date":"24-03-2014","Cars":["Cheap","Expensive"]}';
$obj = json_decode($str);
echo $obj->date;
// 24-03-2014
Usually a $my_obj = json_decode($_POST['jsonstring'], 1); (true supply means it'll be returned as an assoviative array) should be the way to go. If I were you I'd probably try a var_dump($my_obj); to see what actually comes through. If it doesn't work you'll want to make sure that you correctly submit a valid json string, e.g. JSON.stringify();
You should check out the PHP doc page for json_decode here.
By default, unless you pass true as the second parameter for json_decode, the function call will return an object, which you can access the members of by using:
$meta->date
The arrow operator will allow you to access object values, not the square brackets or a dot.
I'm making a generic php class which autoloads values into an object from a Database
To set properties I use this:
$object->$propertyName = $valueFromDB; where the value of propertyName is comes from the mysql field name..
Now I want to push something onto an array in a similar fashion:
This works..
$object->$arryName = array();
But this doesn't..
$object->$arryName[] = "test";
How can I work around this?
$object->{$arryName}[] = "test"
The curly braces change the order of operations and will make PHP evaluate the variable name before the hard braces.
If you want to do a associative array, this gets a little more complicated:
$object->{$arryName}[$keyname] = "test"
In this case, you can put curly braces around $keyname but it's entirely optional.
On a related note.. variable variables are usually - but not always - a sign of something screwy. They're also a pain to whoever is coming after you who has to debug, refactor, do any grepping, etc. If you must use them, fine but make sure you've considered the ramifications.
Without resorting to using regex, is there a way to do so if I saved my array into json format? I'm interesting in json only because I'm using mongodb so the output comes out in json format. I have a field called docroot which is essentially a directory path.
docroot : "secure.unstable.qa.example.com"
The only two pieces that could change depending on other factors are unstable and qa. What I'm hoping for is a way to place "markers" so that they could easily be replaced with an appropriate variable.
For example:
docroot : "secure.{STREAMS}.{ENV}.example.com"
docroot : "unsecure.{STREAMS}.{ENV}.example.com"
If the variables are guaranteed to be in some specific order (they are, according to your example), then I would advise not reinventing the wheel:
// Assuming $json contains your JSON
$streams = 'foo';
$env = 'bar';
$data = json_decode($json, TRUE);
var_dump($data['docroot']); // "secure.%s.%s.example.com"
var_dump(sprintf($data['docroot'], $streams, $env)); // "secure.foo.bar.example.com"
If the variables are not guaranteed, or you'd just like to use more descriptive placeholders, just pick some unique delimiters (some character or set of characters that is unlikely to actually appear in your data), and use str_replace().
This question already has answers here:
Access object property with disallowed character in property name
(2 answers)
Closed 4 months ago.
I need to access a php object property which I specify as variable.
$phpObj->$property
This $property might contain chars like dash(-), quotes, percent, even whitespace ect. PHP does not allow these chars to be used as variable names, resulting which I am unable to access these properties.
What would be a good solution to handle this? I'm open with encoding the $property to something alphanumeric first and then using it as property variable but this encoding should be unique for a particular string.
Eg, I want to make sure that $phpObj->First-Prop and $phpObj->first-prop should be identified differently.
$propertyName = 'property-name';
$phpObj->{$propertyName} = ...
$phpObj->{"property-name"} = ...
only this may be problem:
$phpObj->First-Prop and $phpObj->first-prop
variable/function/method/property definitions in php are not case-sensitive...
not sure what you wish to achieve here but.
But
you would be best to impliment a whitelist of useable chars, a-zA-Z0-9 im guessing possible _. then you can assign the property knowing that all of the letters are allowed in php.
i dont understand why the properties need unique property names, surely a property of key with a unique value would achieve a similiar thing, could be appended to everything.
php is not case sensetive so $phpObj->First-Prop and $phpObj->First-Prop will take the last property.
i hope that helps, if you have any more on the implimentation and more importantly what you are trying to achieve i'll do my best to help
After hours of debugging, I found an error in one of my scripts. For saving different event types in a database, I have an array of unique data for each event that can be used to identify the event.
So I basically have some code like
$key = md5(json_encode($data));
to generate a unique key for each event.
Now, in some cases, a value in the $data array is an integer, sometimes a string (depending on where it comes from - database or URL). That causes the outputs of json_encode() to be different from each other, though - once including quotes, once not.
Does anybody know a way to "unify" the variable types in the $data array? That would probably mean converting all strings that only contain an integer value to integer. Anything else I have to take care of when using json_encode()?
array_walk_recursive combined with a function you have written to the effect of maybe_intval which performs the conversion you talk about on a single element.
EDIT: having read the documentation for array_walk_recursive more closely you'll actually want to write your own recursive function
function to_json($obj){
if(is_object($obj))
$obj=(array)$obj;
if(is_array($obj))
return array_map('to_json',$obj);
return "$obj"; // or return is_int($obj)?intval($obj):$obj;
}