rtom
rtom

Reputation: 209

Recursively go through multidimensional array with varying levels of depth

I am trying to go through multidimensional array, I have an array of keys that I want to find in the multidimensional array, and after i found it, assaign its value to said key. For example I have an key Keyword and I have an array

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
             ) 
        ) 
    ) 
)

Well I tried to do it recursively, foreach($array as $key => $value) if $value is an array, then i need to go another level inside. I managed to get the values assigned to keys that i wanted, but instead of 12 items I got 100 of them.

Array of cloumn names

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

Working function for CSV format

 public function LoadCsvReport($adSystemColumnsColumns = array())
{
    require "config.php";
    $key = array();
    $flag = false;


    $csvfile = fopen(dirname(__FILE__) . "/result.csv", "r");

    while ($file = fgetcsv($csvfile)) {
        if (!$flag) {
            /*Loop through config array which contains names of columns of our interest
              If row from file contains name from config, then that name will have assigned
              index of that column
            */
            foreach ($bing as $name)
                if ($value = array_search($name, $file)) {
                    $key[$name] = $value;
                    $flag = true;
                }
            //After column indexes are assigned to names skip current row
            if ($flag)
                continue;
        }
        if ($flag) {

            foreach ($key as $columnName => $index) {
                /*Get columnname and index, items from $file[$index] are assign to 
                  corresponding array with columnName as index
                */
                if ($file[$index] === "-")
                    break;
                $this->report[$columnName][] = $file[$index];
                //$key[$index] = array($item => $file[$item]);

            }
        }
    }
    fclose($csvfile);
    return $this->report;
}

Upvotes: 0

Views: 1021

Answers (2)

L. Herrera
L. Herrera

Reputation: 490

I re-created your arrays, if my understanding is right, you want to recursively get the values by the given array $bing and get the designated values. Check this:

$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>';

EDIT

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>';

I updated my answer so that even you add even more levels it will recursively find the specific values given by your array of column names. Try exploring RecursiveArrayIterator

Upvotes: 1

Ankush Tanwar
Ankush Tanwar

Reputation: 239

Here you go with a generic function for doing the same

    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']

Upvotes: 0

Related Questions