2013-03-09 86 views
-2

我想寫一個函數,它將搜索多維數組中的值並返回祖父母的鍵。請參閱下面的數組層次結構。PHP搜索多維數組,用於祖父母的值和返回鍵

Array 
(
[results] => Array 
    (
     [quote] => Array 
      (
       [0] => Array 
        (
         [@attributes] => Array 
          (
           [symbol] => VFORX 
          ) 
         [LastTradePriceOnly] => 24.79 
        ) 
       [1] => Array 
        (
         [@attributes] => Array 
          (
           [symbol] => VGSTX 
          ) 
         [LastTradePriceOnly] => 21.77 
        ) 
       [2] => Array 
        (
         [@attributes] => Array 
          (
           [symbol] => HPQ 
          ) 
         [LastTradePriceOnly] => 21.00 
        ) 
      ) 
    ) 
) 

例如,我要搜索的「符號」鍵爲值「HPQ」並返回任一的21.00的LastTradePriceOnly值或祖父母的關鍵是[2]。

在此先感謝您提供的任何幫助,以幫助我入門。

+3

請開始寫您的最終一些代碼,以便我們可以建議一些 – 2013-03-09 19:22:07

+0

是的,這是最適合你分享,你已經嘗試代碼。這將有助於社區幫助你。 – 2013-03-09 19:37:20

回答

1

Hast的答案是解決方案,但要添加,您還可以在foreach語句中使用數組的鍵來獲得'祖父母'。乾杯。

<?php 

$array = array(); // this is your array 
$value = 'HPQ'; 
$result = null; 
$grandparent = null; 

foreach($array['results']['quote'] as $quote_index => $quote) { 
    if ($quote['@attributes']['symbol'] == $value) { 
     $result = $quote['LastTradePriceOnly']; 
     $grandparent = $quote_index; 
    } 
} 
+0

謝謝你和哈斯。這工作完美。我將在未來嘗試分享我的代碼。 – GrandTomato 2013-03-09 19:47:29