0

I have an array that looks something like this:

Array
(
    [100] => Array
        (
            [room_id] => 100
            [name] => Town Center
        )

    [110] => Array
        (
            [room_id] => 110
            [name] => Coffee Shop
            [pin_id] => 7146
            [pin_x] => 570
            [pin_y] => 150
        )
)

I was wondering if there was a way that I could obtain a specific value, if the "pin_id" key was there. So for example:

Array
(
    [100] => Array
        (
            [room_id] => 100
            [name] => Town Center     <-- No "pin_id" so I DON'T need this value
        )

    [110] => Array
        (
            [room_id] => 110
            [name] => Coffee Shop     <-- I want to OBTAIN this value
            [pin_id] => 7146          <-- Since the "pin_id" key is here
            [pin_x] => 570
            [pin_y] => 150
        )
)

I've tried using foreach, but it gets to complicated for me. I'm still very new with arrays, and not so familiar with the terminology/functions.

3 Answers 3

1

Easy use the PHP function array_key_exists

You may have to go through a foreach loop since you are using a multidimensional array:

$names = [];
foreach($array as $e)
{
  if(array_key_exists('pin_id', $e)) {
        echo "The 'pin_id' element is in the array";
      $names[] = $e['name'];
  }
}

And now $names include all you names values

Sign up to request clarification or add additional context in comments.

Comments

0
foreach ($your_big_array as $arr) {
    if ($arr['pin_id'] == 'some_value') $i_need_this = $arr['name'];
}

Comments

0
function search_key( $array, $key ) {
    $results = array();
    if ( is_array( $array ) ) {
        if ( isset( $array[$key] ) && $array[$key] == $key )
            $results[] = $array;
        foreach ( $array as $subarray )
            $results = array_merge( $results, tm_search_key_value( $subarray, $key ) );
    }
    return $results;
}

USAGE:

search_key( $array, 'pin_id');

Search specific KEY from Multidimentional, It will return array of that specific key.

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.