用数组替换PHP关联数组值(字符串)

时间:2012-03-07 00:44:38

标签: php multidimensional-array for-loop associative-array

我想将'BLOCKS'数组中的'baz'值替换为标题匹配的'BAZ'数组中的数组。

我试过爆炸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)
            )              
          );

2 个答案:

答案 0 :(得分: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];
        }
    } 
}

答案 1 :(得分: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.
            }
        }
    }
}

User是Gar's Infotech的高级开发人员http://garsinfotech.com