caberg caberg - 4 months ago 8
PHP Question

How to get array when match the value, then use it

2 days searching in googles and try using a lot of code but nothing works.

ok lets get to the point

right now i have dummy page just to store datas that i need using Advanced Custom Field in wordpress and i named it page_categories-animation.php

then in my index.php, i wrote this

// get post id from page feature animation categories
$anim_id = url_to_postid('feature-animation-categories');
// get all the data from it
$variable = get_field('animCategory', $anim_id);

print_r($variable);


the output of $variable is like this (actually its have 20 arrays but I use 2 arrays just so easy to understand)

Array
(
[0] => Array
(
[category_name] => Coffee Machines
[categoryId] => 12
[animateTitle] => Better ways to cleaner dishes.
[animateIcon] =>
[animateLink] => http://google.com
[animateBG] =>
[fram1] => Array
(
[ID] => 315
[id] => 315
[title] => coffee-frame1
[filename] => coffee-frame1.png
)

[fram2] => Array
(
[ID] => 316
[id] => 316
[title] => coffee-frame2
[filename] => coffee-frame2.png
)
)

[1] => Array
(
[category_name] => Cooking & Baking
[categoryId] => 13
[animateTitle] => Better ways to cleaner dishes.
[animateIcon] =>
[animateLink] => http://google.com
[animateBG] =>
[fram1] => Array
(
[ID] => 318
[id] => 318
[title] => cookie-frame1
[filename] => cookie-frame1.png
)

[fram2] => Array
(
[ID] => 319
[id] => 319
[title] => cookie-frame2
[filename] => cookie-frame2.png
)
)
)


my question is how i can use the array that match the value, in this case just assume we already have categoryId 13 and i want to grab the array which have categoryId 13 and use it.

any help would be greatly I appreciated, thx before and sorry for my bad english ^_^

Answer

This will work:

$use_array = [];

foreach($variable as $v) // loop through your array of data
{
    if($v['categoryId'] == 13) // look for categoryId = 13
    {
        $use_array = $v; // save this array for later use
        break; // quit looping to save processing time and resources
    }
}

print_r($use_array); // this will be your array with categoryId = 13