2012-03-07 119 views
0

我想用'BAZ'數組中的數組替換'BLOCKS'數組中的'baz'值,這些數組的標題匹配。用數組替換PHP關聯數組值(字符串)

我試過爆炸BLOCKS ['baz'],然後循環遍歷結果,並做一個str_replace無濟於事。我確信有一個更簡潔和直接的解決方案。

請參閱我想要完成的底部的DESIRED OUTPUT。非常感謝!

BLOCKS 

    array 
     0 => 
     array 
      'foo' => string 'block1' (length=6) 
      'bar' => string '/uploads/commercial/pdf.pdf' (length=27) 
      'baz' => string '372|371' (length=7) 
     1 => 
     array 
      'foo' => string 'block2' (length=6) 
      'bar' => string '/uploads/commercial/pdf.pdf' (length=27) 
      'baz' => string '371' (length=3) 

    BAZ 

    array 
     372 => 
     array 
      'wibble' => string 'building2' (length=9) 
      'wobble' => int 235000 
      'wubble' => string 'office|medical' (length=14) 
     371 => 
     array 
      'wibble' => string 'building1' (length=9) 
      'wobble' => int 252000 
      'wubble' => string 'office' (length=6) 

    DESIRED OUTPUT 

    array 
     0 => 
     array 
      'foo' => 'block1' 
      'bar' => '/uploads/commercial/pdf.pdf' 
      'baz' => array(
      372 => 
       array 
       'wibble' => string 'building2' (length=9) 
       'wobble' => int 235000 
       'wubble' => string 'office|medical' (length=14) 
      371 => 
       array 
       'wibble' => string 'building1' (length=9) 
       'wobble' => int 252000 
       'wubble' => string 'office' (length=6) 
      ); 

     1 => 
     array 
      'foo' => string 'block2' (length=6) 
      'bar' => string '/uploads/commercial/pdf.pdf' (length=27) 
      'baz' => array(
      371 => 
       array 
       'wibble' => string 'building1' (length=9) 
       'wobble' => int 252000 
       'wubble' => string 'office' (length=6) 
      )    
     ); 
+0

請新增到目前爲止你已經嘗試了代碼開發高級。 – Marc 2012-03-07 00:46:43

回答

1

試試這個:

foreach ($blocks as &$block) { 

    $bazIds = explode('|', $block['baz']); 

    unset($block['baz']); // Keep it clean 

    foreach ($bazIds as $bazId) { 

     if (array_key_exists($bazId, $baz) { 
      $block['baz'][$bazId] = $baz[$bazId]; 
     } 
    } 
} 
+0

謝謝邁克,這就是我以後的樣子。根據我的需求創建我所需要的更清潔,而不是直接替換它。 – juddlyon 2012-03-07 23:58:25

+0

對不起,S.O.相當新穎。並無法弄清楚如何接受它。他們不會在任何地方記錄支票圖標! – juddlyon 2012-03-12 16:28:19

0

可以使用的foreach遍歷數組和檢查的關鍵。如果你找到的期望鍵然後將值類似下面的代碼

foreach($BLOCKS as $key -> $value){ 
    if(is_array($value){ 
     foreach($BLOCKS[$key] as $key1 -> $value){ 
      if($key1=='baz'){ 
       //logic here for string split using token | and create a new array from value 
       // You need to put $$ for using value as variable. 
      } 
     } 
    } 
} 

用戶在雀鱔的盈富泰克http://garsinfotech.com