1

I have a data structure like that:

Array(
    [494] => Array(
        [meta_key] => course_494_access_from
        [expires_in] => 95
    ),
    [498] => Array(
        [meta_key] => course_498_access_from
        [expires_in] => 122
    ),
    [502] => Array(
        [meta_key] => course_502_access_from
        [expires_in] => 30
    ),
    [506] => Array(
        [meta_key] => course_506_access_from
        [expires_in] => 365
    )
)

and I like to ask, if there is a way to get the expires_in value by searching the course_502_access_from

So, in example, I like to know if there is a way to perform an array search in the given structure, by usign the term course_502_access_from and then get the value 30 that corresponds to sub array key expires_in.

3 Answers 3

2

In general case when there are multiple occurences of searching string ('course_502_access_from') you may use array_filter with array_map. Somehow like this:

$result = array_map(
    function ($v) {
        return $v['expires_in'];
    },
    array_filter($array, function ($v) {
        return $v['meta_key'] == 'course_502_access_from';
    }
);

print_r($result);
Sign up to request clarification or add additional context in comments.

Comments

2

I think you can just loop in array and use in_array() function to find your match value

foreach($array as $key => $data)
{
    if(in_array("course_502_access_from",$data))
    {
        echo $array[$key]['expires_in'];
        break;
    }
}

Working sample here

1 Comment

Adding a break; in the if would avoid useless loops as it appears that there is no twice the same course_502_access_from in the array
1

If the structure never changes and stays that way, its pretty easy, yes:

foreach($your_array as $a) {
    if($a["meta_key"] === "course_502_access_from") {
        return $a["expires_in"];
    }
}

If it does and you get multiple layers ... well, then things start to become complicated. You could create a function and use it recursive ... but that would require more than just these 5 lines of code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.