Join strings and separate with a comma using PHP
arrays, mysql, oop, php
Solution
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.
Problem
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`.