2015-06-20 91 views
1

假設我有這個數組返回值(實際是一個大得多確實):從多維數組

Array 
(
    [CD000000001] => Array 
     (
      [0] => Array 
       (
        [periodo] => 10/2010 
        [incasso] => 15000.00 
        [spesa] => 0.00 
       ) 

      [1] => Array 
       (
        [periodo] => 03/2013 
        [incasso] => 0.00 
        [spesa] => 280.00 
       ) 

     ) 

    [CD000000002] => Array 
     (
      [0] => Array 
       (
        [periodo] => 11/2010 
        [incasso] => 327199.83 
        [spesa] => 0.00 
       ) 

      [1] => Array 
       (
        [periodo] => 03/2013 
        [incasso] => 0.00 
        [spesa] => 3194.90 
       ) 

     ) 
) 

我試圖讓[incasso]值和[SPESA]那場比賽第二級別的第一級數組和[periodo]。因此,例如我尋找CD000000002,如果我找到它,然後我尋找03/2013。如果我找到它,我想返回[incasso]和[spesa]值。 CD000000002和[periodo]都是由for循環構建的,因此我將測試現有值和不存在的值。 其實在我看來,我無法正確訪問第二個數組,我不明白爲什麼。這是我的實際代碼: (在本例中$ CREDITO是CD000000002):

if(isset($flussi[$credito])){ 
    //if I find CD000000002 
     $key = array_search($periodo,$flussi[$credito]); 
    //return the key of the second level array that have the value 03/2013 
     if($key){ 
      $incasso = $flussi[$credito][$key]['incasso']; 
     }else{ 
      $incasso = 0.00; 
    //return the value of [incasso] corresponding to that key 
    }else{ 
     $incasso = '0.00'; 
    } 
    unset($key); 

我在做什麼錯??? 我不想使用foreach循環,但我想要正確地搜索正確的數組索引值。重複問題中提到的功能是我所熟知的,但在這種情況下不適用於性能。數組大小太大每個腳本運行

+0

我正在尋找array_search中的$ periodo。並且在本例中它是2013年3月。我想要的密鑰對[periodo] => '03/2013' –

+0

可能重複[PHP多維數組搜索](http://stackoverflow.com/questions/6661530/php-multi-dimensional-array-search ) – Sean

+0

@Sean兩者是如何相關的?它是在第一級數組的單個項目中搜索單個值。每次我必須搜索時,我不希望每次都使用foreach。 Periodo是一個日期,從月開始從2008年1月到2017年12月每個月(表列),我有100或更多行每次(每個是CD000 ...)我使用類似於該答案中的代碼對於其他腳本,但在這裏我想看看我的代碼有什麼問題! –

回答

3

時間做一個foreach 5.000倍,至少爲了$key = array_search($periodo,$flussi[$credito]);找到periodo的價值,你需要你的陣列從數字鍵改變

Array 
(
    [CD000000001] => Array 
     (
      [0] => Array 
       (
        [periodo] => 10/2010 
        [incasso] => 15000.00 
        [spesa] => 0.00 
       ) 

      [1] => Array 
       (
        [periodo] => 03/2013 
        [incasso] => 0.00 
        [spesa] => 280.00 
       ) 

     ) 
... 

到一個數組,其中periodo的值是關鍵

Array 
(
    [CD000000001] => Array 
     (
      [10/2010] => Array 
       (
        [periodo] => 10/2010 
        [incasso] => 15000.00 
        [spesa] => 0.00 
       ) 

      [03/2013] => Array 
       (
        [periodo] => 03/2013 
        [incasso] => 0.00 
        [spesa] => 280.00 
       ) 

     ) 
...