I have a PHP array:
array
0 =>
array
'cid' => string '18427' (length=5)
1 =>
array
'cid' => string '17004' (length=5)
2 =>
array
'cid' => string '19331' (length=5)
I want to join the values so I can get a string like this:
18427,17004,19331
I tried the implode
PHP function, But I get an error:
A PHP Error was encountered
How can join only the values which are in cid
?
To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.
The join() function is built-in function in PHP and is used to join an array of elements which are separated by a string. Syntax string join( $separator, $array) Parameter: The join() function accepts two parameter out of which one is optional and one is mandatory.
Given two array arr1 and arr2 and the task is to append one array to another array. Using array_merge function: This function returns a new array after merging the two arrays. $arr1 = array ( "Geeks" , "g4g" );
You have to map the array values first:
echo join(',', array_map(function($item) {
return $item['cid'];
}, $arr));
Without closures it would look like this:
function get_cid($item)
{
return $item['cid'];
}
echo join(',', array_map('get_cid', $arr));
See also: array_map()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With