1

Solution

Thanks to @El_Vanja

if ($WPArray[0]['acf']['actor_reels']) {
$actor_reels = array_column($WPArray[0]['acf']['actor_reels'], 'actor_reel_category');
foreach ($actor_reels as $actor_reel) {
    echo $actor_reel[0];
}}

Original Question

I have the following code returning an array:

$WPArray = json_decode("$WPVars", true);
$output = $WPArray[0]['acf']['actor_reels'];
print_r($output);

Returning:

Array ( 
[0] => Array ( 
    [actor_reel_name] => Voice Reel 
    [actor_reel_category] => Array ( 
        [0] => Voicereel 
         ) 
    [actor_reel_url] => www.example.com
    [actor_reel_image] => www.example.com 
    ) 
    
[1] => Array ( 
    [actor_reel_name] => Show Reel 
    [actor_reel_category] => Array ( 
        [0] => Showreel 
     ) 
    [actor_reel_url] => www.example.com
    [actor_reel_image] => www.example.com
    ) 
)

The next part of my script is to be able to get the "Voicereel" and "Showreel" values into a new array (lets say its called $actor_reel_cats) so that they can be used elsewhere in a foreach statement and each actor_reel_category would ultimately display as a button on a webpage.

    <?php foreach($actor_reel_cats as $reel_cat): ?>
            <div class="f_btn">
                <label><input type="radio" name="fl_radio" value="<?= $reel_cat ?>" />
                    <?= $reel_cat ?>
                </label>
            </div>
    <?php endforeach; ?>

The actor_reel_category values are totally dynamic and the list can be added to at any time, for example, the next array [2] may have [actor_reel_category] => Dance Reels (or any other value as they would be customisable by the end-user) so I'm a tad stumped.

Note for Advanced Custom Fields people: This script is outside of WordPress so I can't use any functions that you would normally use such as get_field_object(), unless I was to import/re-create or copy them.

Also, I'm new to StackOverflow so apologies if there are any abnormalities in my request for help here.

TIA

  • Is the structure of that array guaranteed to look like that? If so, recursion is not necessary here. You might want to look into [`array_column`](https://www.php.net/manual/en/function.array-column) to help you with your task. – El_Vanja Apr 26 '21 at 14:29
  • You should post it as an answer (it is ok to answer your own questions on SO) and then remove that edit. Solution edits in the question are harder to spot + the question doesn't appear as answered in the list and won't show up when someone filters answered questions. – El_Vanja Apr 26 '21 at 18:07

1 Answers1

0

Solution

Thanks to @El_Vanja

if ($WPArray[0]['acf']['actor_reels']) {
$actor_reels = array_column($WPArray[0]['acf']['actor_reels'], 'actor_reel_category');
foreach ($actor_reels as $actor_reel) {
    echo $actor_reel[0];
}}