Search code examples
phparraysjsonadvanced-custom-fieldsacfpro

Recursively get specific values from three-dimensional array


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


Solution

  • 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];
    }}