Jump to content

searching and displaying a 'record' in a multidimensional array


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?

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.