递归地遍历具有不同深度级别的多维数组

时间:2016-11-15 09:39:09

标签: php arrays recursion multidimensional-array

我正在尝试通过多维数组,我有一个我想在多维数组中找到的键数组,并且在我找到它之后,将其值赋予所述键。例如,我有一个键<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script> <canvas id="c" width="500" height="500"></canvas>,我有一个数组

Keyword

好吧,我尝试递归地执行,Array ( [root] => Array ( [row] => Array ( [0] => Array ( [Status] => Enabled [Keyword] => Toaletna voda [Campaign] => Lešenari [Adgroup] => Lešenaris [BidStrategyType] => InheritFromParent [Bid] => 0.05 [Matchtype] => Broad [Clicks] => 0 [Impr.] => 0 [Conv.] => 0 ) ) ) ) 如果$ value是一个数组,那么我需要进入另一个级别。我设法获得了分配给我想要的键的值,但是我得到了100个而不是12个项目。

cloumn名称数组

foreach($array as $key => $value)

CSV格式的工作功能

$bing = array(
"Adgroup",
"Campaign",
"Keyword",
"Clicks",
"Impr.",
"Conv.",
"Bid",
"Adgroup"
);

2 个答案:

答案 0 :(得分:1)

我重新创建了你的数组,如果我的理解是正确的,你想通过给定的数组$ bing递归获取值并得到指定的值。检查一下:

$bing = array(
"Adgroup",
"Campaign",
"Keyword",
"Clicks",
"Impr.",
"Conv.",
"Bid",
"Adgroup"
);

$arr = array(
    "root" => array( 
                "row" => array( 
                            array ( 
                                "Status" => "Enabled" 
                                ,"Keyword" => "Toaletna voda"
                                ,"Campaign" => "Lešenari"
                                ,"Adgroup" => "Lešenaris" 
                                ,"BidStrategyType" => "InheritFromParent"
                                ,"Bid" => "0.05" 
                                ,"Matchtype" => "Broad"
                                ,"Clicks" => "0" 
                                ,"Impr." => "0"
                                ,"Conv." => "0") 
                                ) 
                            ) 
);


echo '<pre>';
    print_r($arr);
echo '</pre>';

修改

function GetValues($array, $newArr) {
    $new_arr = array();
    $array_obj = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
    foreach($array_obj as $key => $value) {
       foreach($newArr as $val) {
           if($val == $key) {
               $new_arr[$val] = $value;
           }

       }
    }
    return $new_arr;
}

$new_arr_ = GetValues($arr, $bing);

echo '<pre>';
    print_r($new_arr_);
echo '</pre>';

我更新了我的答案,这样即使您添加更多级别,它也会递归地找到列名称数组给出的特定值。尝试浏览R code

答案 1 :(得分:0)

在这里,您可以使用通用函数来执行相同的操作

    function assignVal ($arr){
        $finalArr = [];
        foreach($arr as $key=>$value){
            if(is_array($value)){
                $return = assignVal($value);
                $finalArr = array_merge($finalArr,$return); 
            }else{
                $finalArr[] = $value;
            }
        }
        return $finalArr;
    }
    // sample array
    $firstArr = ['w'=>['a','b','c'],'d','t'];
    $finalArr = assignVal($firstArr);
    print_r($finalArr); // output ['a','b','c','d','t']