6

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?

3 Answers 3

15

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()

Sign up to request clarification or add additional context in comments.

3 Comments

@Jack.. Thanks for the solution and it worked. But there's a small error in the code $arr needs to be inside the function for the solution with the closures.. :)
array_column()
ah yeah, indeed :)
0
// set a new variable for their the value of cid
$cid = array();

// then loop to call them one by one.
foreach($css as $style){
 foreach($style as $row){
    array_push($cid,$row);
 }
}

// then the new $cid array would contain the values of your cid array
 $cid = array('1','2','3');

note:then you can now implode or watever you want to get the data set you want..

Comments

-1

You can loop through each element

$result = '';
foreach($array as $sub_array){
  $result .= $sub_array['cid'] . ',';
  }
$result = substr($result, -2);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.