PHP搜索数组返回键

时间:2010-06-21 13:05:04

标签: php search arrays

我有一个看起来像这样的数组,我想搜索一个saleref并让它给我PHP中的密钥,我尝试使用array_search但我什么都没收到。或者,我只想显示与salesref搜索相同的数组中的其他值,如果有更好的方法。

 Array
    (
        [xml] => Array
            (
                [sale] => Array
                    (
                        [0] => Array
                            (
                                [saleref] =>  305531
                                [saleline] =>   1
                                [date] => 
                                [team] => WH
                                [manifest] =>       0
                                [qty] =>     1
                                [order_status] => 
                            )

                        [141] => Array
                            (
                                [saleref] =>  306062
                                [saleline] =>   1
                                [date] => 
                                [team] => 
                                [manifest] =>       0
                                [qty] =>     1
                                [order_status] => RECEIVED
                            )

                        [1] => Array
                            (
                                [saleref] =>  306062
                                [saleline] =>   2
                                [date] => 
                                [team] => WH
                                [manifest] =>       0
                                [qty] =>     1
                                [order_status] => 
                            )

2 个答案:

答案 0 :(得分:2)

<?php
function searchSale($needle)
{
    foreach ($data['xml']['sale'] as $id => $sale)
    {
        if ($sale->saleref == $needle)
        {
            return $id;
        }
    }
    return null;
}
?>

答案 1 :(得分:0)

function findkey($val, &$array)
{
   $keys=array();
   foreach ($array as $key=$try) {
     if ($try===$val) {
       $keys[]=$key;
     } else if (is_array($try)) {
       $contained=findkey($val, $try);
       if (count($contained)) {
          $keys[]=$contained;
       }
     }
   }
   return $keys;
}

下进行。