Zach Nicodemous Zach Nicodemous - 4 years ago 454
PHP Question

Echo specific line from each array

I have the following dynamically generated array. The array values can change each time, but the positions remain the same (i.e. name will always be the 2nd item for each array).

How would I echo the same specific line from each array? For example, say I wanted all the names echoed together?

Array
(
[0] => WP_Term Object
(
[term_id] => 437
[name] => 128 GB
[slug] => 128-gb
[term_group] => 0
[term_taxonomy_id] => 437
[taxonomy] => pa_phone-capacity
[description] =>
[parent] => 0
[count] => 88
[filter] => raw
)

[1] => WP_Term Object
(
[term_id] => 19
[name] => AT&T
[slug] => att
[term_group] => 0
[term_taxonomy_id] => 19
[taxonomy] => pa_phone-carrier
[description] =>
[parent] => 0
[count] => 288
[filter] => raw
)

[2] => WP_Term Object
(
[term_id] => 280
[name] => Flawless
[slug] => flawless
[term_group] => 0
[term_taxonomy_id] => 280
[taxonomy] => pa_phone-condition
[description] => Works perfectly.

No noticeable flaws, still in its package or looks like new.

Has zero scratches or scuffs.
[parent] => 0
[count] => 338
[filter] => raw
)

[3] => WP_Term Object
(
[term_id] => 442
[name] => iPhone
[slug] => iphone
[term_group] => 0
[term_taxonomy_id] => 442
[taxonomy] => pa_device
[description] =>
[parent] => 0
[count] => 496
[filter] => raw
)

[4] => WP_Term Object
(
[term_id] => 284
[name] => iPhone 6 Plus
[slug] => iphone-6-plus
[term_group] => 0
[term_taxonomy_id] => 284
[taxonomy] => pa_phone-model
[description] =>
[parent] => 0
[count] => 72
[filter] => raw
)

[5] => WP_Term Object
(
[term_id] => 443
[name] => Smartphone
[slug] => smartphone
[term_group] => 0
[term_taxonomy_id] => 443
[taxonomy] => pa_device
[description] =>
[parent] => 0
[count] => 1352
[filter] => raw
)


I need a solution that will remain dynamic. Sometimes there might be 8 term objects, sometimes there might only be 5 like in the above array. term_id will always be the first, name will always be the second, so on and so forth.

This has been eluding me for at least an hour now and its frustrating me so much :(

Answer Source
echo implode(", ", array_map(function(WP_Term $term){
    return $term->name;
}, $array));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download