Peter
Peter

Reputation: 1296

Exctract values from php array

I have an array like this (this is actually a WordPress category list array):

Array ( [0] => stdClass Object ( [term_id] => 4 ) [1] => stdClass Object ( [term_id] => 6 ) ) 

Is there a way to exctract "term_id" values and assign it to $term variable with comma separated values?

in this case variable should be: $term = 4,6

Thanks for the help !

Upvotes: 0

Views: 64

Answers (1)

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99879

$term = implode(',', array_map(function($o) { return $o->term_id; }, $array));

Or:

$term = array();
foreach($array as $o) $term[] = $o->term_id;
$term = implode(',', $term);

In a function:

function getTerms($array) {
    $term = array();
    foreach($array as $o) $term[] = $o->term_id;
    return implode(',', $term);
}

Upvotes: 4

Related Questions