Can you loop through a multi-dimensional array using the “foreach” function, but only make it output key/value pairs that match a specific value?
| SitePoint Sponsor |
Can you loop through a multi-dimensional array using the “foreach” function, but only make it output key/value pairs that match a specific value?



couldn't you just do something like:
PHP Code:<?
// create array
$starwars = array("princess" => "Leia", "teacher" => "Yoda", "new hope" =>
"Luke", "bad guy" => "Darth", "worse guy" => "The Emperor" );
// returns true
echo in_array("Yoda", $starwars);
// returns false
echo in_array("Obi-Wan", $starwars);
?>
Compwizard
"There are 10 kinds of people in this world -- those who know binary, and those who don't."



check out this page if you have php4:
http://www.devshed.com/Server_Side/P...nip/print_html
Compwizard
"There are 10 kinds of people in this world -- those who know binary, and those who don't."





Following the lead of our admired advisorsOriginally Posted by ogoka
, here is my reply:
Yes you can
- website
Website,
Can you give an example not already mention above?





hmm, not quite sure what you want but here is one example if you want to search 2 dimensional array, you simply do foreach twice
and so on, if you can say more about what you need I (or others) could give you more specific examples....PHP Code:foreach ($data as $key => $val) {
foreach ($val as $subkey => $subval) {
if (strcmp($subkey, 'something') == 0 )
echo ($subkey . ' => ' . $subval);
}
}
Hope that helps!
- website
Website,
Here's an example array:
$birds = array (
'21064' => array('number' => '21064', 'name' => 'Porcelain Cardinals', 'price' => '19.95'),
'21065' => array('number' => '21065', 'name' => 'Porcelain Canaries', 'price' => '19.95'),
'21066' => array('number' => '21066', 'name' => 'Porcelain Doves', 'price' => '19.95'),
'21681' => array('number' => '21681', 'name' => 'Porcelain Cardinal On Branch', 'price' => '9.95'),
'21683' => array('number' => '21683', 'name' => 'Porcelain White Dove', 'price' => '17.95'),
'22798' => array('number' => '22798', 'name' => 'Porcelain Baby Cardinals', 'price' => '14.95'),
'22801' => array('number' => '22801', 'name' => 'Porcelain Cardinals On Branch', 'price' => '37.95'),
'22802' => array('number' => '22802', 'name' => 'Porcelain Bluejays On Branch', 'price' => '37.95'),
'22803' => array('number' => '22803', 'name' => 'Porcelain Doves On Branch', 'price' => '37.95'),
'24795' => array('number' => '24795', 'name' => 'Porcelain Eagle With 2 Flags', 'price' => '29.95')
);
I'm trying to get the foreach loop function to show only all items with a price of $37.95.
Thanks.





PHP Code:$keep = array();
foreach($birds as $bird) {
if ($bird['price'] == '37.95') {
$keep[] = $bird;
}
}
Last edited by anode; May 10, 2003 at 15:18.
TuitionFree — a free library for the self-taught
Anode Says... — Blogging For Your Pleasure
Thanks for all your help... I figured it out!
Bookmarks