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.
Related
This question already has answers here:
How to pass an array within a query string?
(12 answers)
Closed 4 years ago.
I have an array of parameter values (with matching parameter names) in my request URL, like this:
?my_array_of_values=First&my_array_of_values=Second
In a Java servlet, I can detect them like this:
ServletRequest request = ...;
String[] myArrayOfValues = request.getParameterValues("my_array_of_values");
And this will result in:
myArrayOfValues[0] = "First";
myArrayOfValues1 = "Second";
...which is what I want.
However, I am not sure how to get the same results in PHP. For the same (above) parameters, when I try:
print_r($_GET);
it results in
Array ( [my_array_of_values] => Second )
...i.e., the "First" parameter is lost.
I can see why this happens, but is there a way to detect such an array of parameter values in PHP as you can in Java/servlets? If not, is there a recommended workaround or alternative way of doing it?
I don't know about the strange magic that happens in a Java environment, but query params must have different names or else they will overwrite each other.
In the example of ?my_array_of_values=First&my_array_of_values=Second only the last given value is returned. It is the same as assigning different values to the same variable one after the other.
You may retrieve a single parameter as array though, by using angle brackets after the parameter name:
?my_array_of_values[]=First&my_array_of_values[]=Second
In that case $_GET['my_array_of_values'] will be an array with all the given values.
See also: Authoritative position of duplicate HTTP GET query keys
This question already has answers here:
How to modify an array's values by a foreach loop?
(2 answers)
Closed 4 months ago.
I was wondering if it is possible to edit the current object that's being handled within a foreach loop
I'm working with an array of objects $questions and I want to go through and look for the answers associated with that question object in my db. So for each question go fetch the answer objects and update the current $question inside my foreach loop so I can output/process elsewhere.
foreach($questions as $question){
$question['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}
There are 2 ways of doing this
foreach($questions as $key => $question){
$questions[$key]['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}
This way you save the key, so you can update it again in the main $questions variable
or
foreach($questions as &$question){
Adding the & will keep the $questions updated. But I would say the first one is recommended even though this is shorter (see comment by Paystey)
Per the PHP foreach documentation:
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
Surely using array_map and if using a container implementing ArrayAccess to derive objects is just a smarter, semantic way to go about this?
Array map semantics are similar across most languages and implementations that I've seen. It's designed to return a modified array based upon input array element (high level ignoring language compile/runtime type preference); a loop is meant to perform more logic.
For retrieving objects by ID / PK, depending upon if you are using SQL or not (it seems suggested), I'd use a filter to ensure I get an array of valid PK's, then implode with comma and place into an SQL IN() clause to return the result-set. It makes one call instead of several via SQL, optimising a bit of the call->wait cycle. Most importantly my code would read well to someone from any language with a degree of competence and we don't run into mutability problems.
<?php
$arr = [0,1,2,3,4];
$arr2 = array_map(function($value) { return is_int($value) ? $value*2 : $value; }, $arr);
var_dump($arr);
var_dump($arr2);
vs
<?php
$arr = [0,1,2,3,4];
foreach($arr as $i => $item) {
$arr[$i] = is_int($item) ? $item * 2 : $item;
}
var_dump($arr);
If you know what you are doing will never have mutability problems (bearing in mind if you intend upon overwriting $arr you could always $arr = array_map and be explicit.
This question already has answers here:
How to modify an array's values by a foreach loop?
(2 answers)
Closed 4 months ago.
I was wondering if it is possible to edit the current object that's being handled within a foreach loop
I'm working with an array of objects $questions and I want to go through and look for the answers associated with that question object in my db. So for each question go fetch the answer objects and update the current $question inside my foreach loop so I can output/process elsewhere.
foreach($questions as $question){
$question['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}
There are 2 ways of doing this
foreach($questions as $key => $question){
$questions[$key]['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}
This way you save the key, so you can update it again in the main $questions variable
or
foreach($questions as &$question){
Adding the & will keep the $questions updated. But I would say the first one is recommended even though this is shorter (see comment by Paystey)
Per the PHP foreach documentation:
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
Surely using array_map and if using a container implementing ArrayAccess to derive objects is just a smarter, semantic way to go about this?
Array map semantics are similar across most languages and implementations that I've seen. It's designed to return a modified array based upon input array element (high level ignoring language compile/runtime type preference); a loop is meant to perform more logic.
For retrieving objects by ID / PK, depending upon if you are using SQL or not (it seems suggested), I'd use a filter to ensure I get an array of valid PK's, then implode with comma and place into an SQL IN() clause to return the result-set. It makes one call instead of several via SQL, optimising a bit of the call->wait cycle. Most importantly my code would read well to someone from any language with a degree of competence and we don't run into mutability problems.
<?php
$arr = [0,1,2,3,4];
$arr2 = array_map(function($value) { return is_int($value) ? $value*2 : $value; }, $arr);
var_dump($arr);
var_dump($arr2);
vs
<?php
$arr = [0,1,2,3,4];
foreach($arr as $i => $item) {
$arr[$i] = is_int($item) ? $item * 2 : $item;
}
var_dump($arr);
If you know what you are doing will never have mutability problems (bearing in mind if you intend upon overwriting $arr you could always $arr = array_map and be explicit.
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.
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.