Jump to content

[SOLVED] search in an array


poe

Recommended Posts

i have an array:

Array
(
    [0] => Array
        (
            [planid] => 1
            [price] => 10
            [term] => 1
        )

    [1] => Array
        (
            [planid] => 3
            [price] => 25
            [term] => 2
        )

    [2] => Array
        (
            [planid] => 7
            [price] => 50
            [term] => 3
        )

)

 

how do i search the 'planid' values and return the matching 'price' value

 

ie search planid = 7, the return would be $myarray['price'] = 50

or if i search on planid and want matching term. ie search planid =3, $myarray['term'] = 2

Link to comment
https://forums.phpfreaks.com/topic/76422-solved-search-in-an-array/
Share on other sites

This is where a foreach loop will really be helpful:

 

<?php
// Assume $records holds your array declared above
function searchPlans($records, $s, $val)
{
  foreach ($records as $r)
  {
    if ($r['planid'] == $val)
    {
      return $r[$s];
    }
  }
}

$id    = 1;
$price = searchPlans($records, 'price', $id);
$term  = searchPlans($records, 'term', $id);
?>

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.