1

I have the following array (example, real one is larger)

Array
(
    [0] => Array
        (
            [984ab6aebd2777ff914e3e0170699c11] => Array
                (
                  [id] => 984ab6aebd2777ff914e3e0170699c11
                  [message] => Test1

        )

    [1] => Array
        (
            [ca403872d513404291e914f0cad140de] => Array
                (
                  [id] => ca403872d513404291e914f0cad140de
                  [message] => Test2
                )

        )

    [2] => Array
        (
            [ca403872d513404291e914f0cad140de] => Array
                (
                  [id] => ca403872d513404291e914f0cad140de
                  [message] => Test3

        )

    [3] => Array
        (
            [ca403872d513404291e914f0cad140de] => Array
                (
                  [id] => ca403872d513404291e914f0cad140de
                  [message] => Test4
                )

        )
)

Now I want to somehow "access" the subarray with a given id, e.g. access the subarray with ID 984ab6aebd2777ff914e3e0170699c11 and then proceed to use this array in a foreach like this..

foreach ($array_with_specific_id as $event) {
    echo $event['message'];
}

Is this possible?

Edit:

DB code to produce array in my model:

  public function get_event_timeline($id)
   {
     $data = array();
      foreach ($id as $result) {
          $query = $this->db->query("SELECT * FROM event_timeline WHERE id = ?", array($result['id']));
          foreach ($query->result_array() as $row)
          {
               array_push($data, array($row['id'] => $row));
          }
      }

      return $data;
   }
4
  • it requires two forach using main array, and for that example yes you can. Commented Feb 5, 2013 at 16:35
  • How will the array been populated? from database? Commented Feb 5, 2013 at 16:35
  • Yup, I will add the DB code Commented Feb 5, 2013 at 16:37
  • you could try array_search() Commented Feb 5, 2013 at 16:39

3 Answers 3

1

When populating your array from the database you can cerate an additional $index array like the following scheme:

$index = array (
    '984ab6aebd2777ff914e3e0170699c11' => ReferenceToElementInData,
    'ca403872d513404291e914f0cad140de' => ReferenceToElementInData,
    // ...
)

This can give you quick access to the elements via their id without an additional foreach loop. Of course it will need additional memory, but this should be ok as you will only save refrences to the original data. However, test it.

Here comes an example:

public function get_event_timeline($id)
{
  $data = array();

  // create an additional index array
  $index = array();

  // counter 
  $c=0;

  foreach ($id as $result) {
      $query = $this->db->query("SELECT * FROM event_timeline WHERE id = ?", array($result['id']));

      // every entry in the index is an array with references to entries in $data
      $index[$result['id']] = array();

      foreach ($query->result_array() as $row)
      {
           array_push($data, array($row['id'] => $row));
           // create an entry in the current index
           $index[$row['id']][] = &$data[$c];
           $c++;
      }
  }

  return array (
      'data' => $data,
      'index' => $index
  );
}

Now you can access the elements via the index array without an additional foreach loop:

$entry = $index['984ab6aebd2777ff914e3e0170699c11'][0];

If there are multiple results per $id (as you mentioned in the comments you can access them using index greater then zero:

$entry = $index['984ab6aebd2777ff914e3e0170699c11'][1];
$entry = $index['984ab6aebd2777ff914e3e0170699c11'][2];

You can get the count of items per $id by calling

$number = count($index['984ab6aebd2777ff914e3e0170699c11']);

That's much the same like indexes that where used in databases to speed up queries.

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

4 Comments

This seems to work thanks.. I have got a little other issue though. The Query could produce multiple results per flight_id.. Only one works right now. Any idea how to fix that? I should loop trough the multiple events for each ID
I'm not sure if understood you correctly.. I such cases you expect that my code : $entry = $index[$flight_id] will return both records, yes?
Yes, exactly! But it could be more than two records
Brilliant! With some minor changes working perfectly now. Thanks so much!
0

I'd probably just get rid of the containing array as it seems unnecessary. However, you could do something like:

function get_message($specific_id, $arrays) {
    foreach($arrays as $array) {
        if(in_array($specific_id, $array)) {
            return $array['message'];
        }
    }
}

I haven't had a chance to test this, but it should work.

1 Comment

What is the best way to get rid of the containing array? Check my post to see the model code
0
function doTheJob($inputArray, $lookingFor) {

    foreach ($inputArray as $subArray) {
        foreach ($subArray as $subKey => $innerArray) {
            if ($subKey == $lookingFor) {
                return $innerArray;
            }
        }
    }
    return NULL;
}

Alternatively, you can use array_filter instead of outer foreach.

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.