Jump to content

searching and displaying a 'record' in a multidimensional array


Cinner

Recommended Posts

I have a multidimensional array that fills with data from a database. The array could look like this:

 

Array
(
    [0] => Array
        (
            [guests] => Array
                (
                    [name] => Barbara Bouchet
                    [id] => 32
                    [photo] => /bouchet.jpg
                    [bio] => This is her biography.


                )

        )

    [1] => Array
        (
            [guests] => Array
                (
                    [name] => Edwige Fenech
                    [id] => 3
                    [photo] => /fenech.jpg
                    [bio] => I'm a great actress.
                )

        )

)

 

This is how the array is composed:

 

$posts[] = array(
			'guests' => array(
				'name' => $row['name'],
				'id' => $row['guestID'],
				'photo' => $row['photourl'],
				'bio' => $row['biography']
		       	),
			);

 

Let's say I want to display all the information of a particular guest, but I only know his 'id' (like $guestID = 3). How do I do this? I think I would need to know which array key belongs to that 'id' and them I could just use something like echo $posts[1]['guests']['name'] to display the data, right?

<?php
function myArraySearch($haystack, $needleName, $needleVal) {
    if (!is_array($haystack)) {
          return false;
    }

    foreach ($haystack as $key => $val) {
           if (is_array($haystack[$key])) {
                 if (myArraySearch($haystack[$key], $needleName, $needleVal)) {
                        return $haystack[$key];
                 }
           }else {
                 if ($key == $needleName) {
                       if ($val == $needleVal) {
                            return true;
                       }
                 }
           }
    }
   
    return false;
}
?>

 

Maybe that will work?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.