How to access object property when property name contains - (hyphen) [duplicate] - php

This question already has answers here:
How do I access this object property with an illegal name?
(2 answers)
Closed 10 months ago.
I need an escape sequence for - or the minus sign for php. The object has a name-value pair where the name happens to be having - between 2 words.
I can't do this using \ the standard escape sequence (- isn't anyways documented).
I can store the name in a $myvariable which can be used but out of curiosity is it possible to do the following?
$myobject->myweird-name
This gives an Error because of -

This is what you need:
$myobject->{'myweird-name'};

If you need to look up an index, there are a couple of ways of doing it:
// use a variable
$prop = 'my-crazy-property';
$obj->$prop;
// use {}
$obj->{'my-crazy-property'};
// get_object_vars (better with a lot of crazy properties)
$vars = get_object_vars($obj);
$vars['my-crazy-property'];
// you can cast to an array directly
$arr = (array)$obj;
$arr['my-crazy-property'];
If you need to work within a string (which is not your best idea, you should be using manual concatenation where possible as it is faster and parsed strings is unnecessary), then you should use {} to basically escape the entire sequence:
$foo = new stdClass();
$foo->{"my-crazy-property"} = 1;
var_dump("my crazy property is {$foo->{"my-crazy-property"}}";
Since you mentioned that this is LinkedIn's API which, I believe, has the option of returning XML, it might be faster (and possibly cleaner/clearer) to use the XML method calls and not use the objects themselves. Food for thought.

Related

How can i use :: as a character within my variable in PHP

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.

Join strings and separate with a comma using PHP [duplicate]

This question already has answers here:
Implode all the properties of a given name in an array of object - PHP [duplicate]
(6 answers)
Closed 2 years ago.
Using PHP, I would like to select certain values from an array of objects, join them to form one continuous string separated by commas, and save this to a variable named $isbn.
I have an array of objects named $items. A var_dump($items) produces this. I need to select the item_isbn value.
My desired result is;
echo $isbn
// would produce
// '0-7515-3831-0,978-0-141-38206-7,978-1-30534-114-1'
Getting rid of the hyphens would be a bonus but I think I can achieve this using str_replace.
Here we go:
$isbnList = [];
foreach ($arrayObject as $item) {
if (isset($item->item_isbn)) {
$isbnList[] = $item->item_isbn;
}
}
$isbn = implode(",", $isbnList);
Check it:
echo $isbn;
For your information:
The foreach works because it's an array. It doesn't care each of the item inside it.
Each of the object ($item) in the loop is the default object of php (as the dump data you provided). Which is supposed to be called as $object->property. This object's property are not sure to always available, so checking whether it's available by php built-in function names isset() is essential.
By knowing implode() is built-in function from php to build a string with separator base on an one side array (means each of item in this one side array must be a scalar value (int, string)). We build this array to ready for the call.
The rest is just about syntax to how-to work with array or object... You can easily lookup on php manual page, eg: http://php.net/manual/en/language.types.array.php
Most popular programming languages nowadays provide us built-in function like this implode(), just different naming.

Single arrow vs double arrow mix and match [duplicate]

This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 6 years ago.
I frequently see $var->another_var, or $somevar=>yet_another, or even $third_var->another=>$fourth_var in various snippets of code.
Is there some super amazing info-graphic somewhere that clearly explains the various usages and what they mean, specifically within a PHP context?
(In my case, using Drupal, which uses LOTS of arrays, but probably useful in lots of other CMSs / frameworks.)
EDIT: I have since been informed about a catch-all page that has a very useful, encyclopedic list of various symbols and syntaxes. However, I believe one section NOT covered there is the mix-and-match combo of $var->element=>$anothervar.
Single arrow - T_OBJECT_OPERATOR
->
This is used for access to an object property and the value associated with that property.
$object->property='value'
I have a dog and his name is Captain
$dog->name='Captain';
Now I have access to properties of my dog. The property that we have set is name
$dogName=$dog->name;
echo $dogName;
Will output: Captain
I can also add other properties and their associated value to my object.
$dog->weight='57lbs';
Now my object has two properties associated with it, name and weight.
Double arrow - T_DOUBLE_ARROW
=>
As is stated in the documentation an array is just a map of comma separated keys and the values associated with the key. The double arrow is essentially an assignment operator that assigns, or associates, the value to a key.
$array = array("key" => "value");
Again using the dog example.
$dog = array("name" => "Captain", "weight" => "57lbs");
And we can access values in my dog array by the respective keys.
$fatDog = $dog["weight"];
echo $fatDog;
Will output: 57lbs
Combinations of single and double arrow
$object->property=>$value;
This combines object/property with key/values. If we break it down into it's constituents it can make things much more clear.
We know that $object->property will yield the value associated with the property. Lets start by associating that with a variable:
$valueAssociatedWithProperty = $object->property;
Using substitution into the original gives:
$valueAssociatedWithProperty => $value;
We have seen that before it is just the key/value of an array! Lets apply this to the dog example and see what comes out:
$dog->name="Captain";
$description="He is crazy";
$array = array($dog->name => $description);
// $array = array("Captain" => "He is crazy");
$whatIsCaptain = $array["Captain"];
echo $whatIsCaptain;
He is crazy
I hope this helps.
Also look HERE for all the references you could ever hope for!
$var->another_var is "property another_var of object referenced by $var".
$somevar=>yet_another is used in array definitions, like this: $arr = array($somevar => yet_another). It would define an associative property with key equal to the value of variable $somevar, and value equal to the constant yet_another.
$third_var->another=>$fourth_var can be rewritten so it becomes more clear:
array( /*key=*/ ($third_var->another) => /*value=*/ $fourth_var )`

Numbers in quotes using json_encode() [duplicate]

This question already has answers here:
How can I force PHP's json_encode integer values to be encoded as String?
(3 answers)
Closed 1 year ago.
Various 3rd party companies are forcing us to use non-conventional code and produce non-standard output.
We are using standard json_encode() to output a JSON variable in JS/HTML which looks like:
"custom":{"1":2,"2":7,"3":5}
Now they tell us this isn't working for them, they need it this way:
"custom":{"1":"2","2":"7","3":"5"}
Can I force PHP to wrap quotes arround numbers? Maybe using cast (string) when we build the object before encoding?
Mainly, we need an opposite of the following option bitflag:
JSON_NUMERIC_CHECK (integer)
Encodes numeric strings as numbers. Available since PHP 5.3.3.
But I doubt this exists.
Guess you need to fix this yourself. I can't think of a built-in function, but you can write your own:
function stringify_numbers($obj) {
foreach($obj as &$item)
if(is_object($item) || is_array($item))
$item = stringify_numbers($item); // recurse!
if(is_numeric($item)
$item = (string)$item;
return $obj;
}
Now you can use json_encode(stringify_numbers($yourObject))
If you're building your json data from a one-dimensional array, you can use
echo json_encode(array_map('strval', $data));
This technique will unconditionally convert all values to strings (including objects, nulls, booleans, etc.).
If your data might be multidimensional, then you'll need to call it recursively.

Accessing PHP object properties when property name has non allowed chars [duplicate]

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

Categories