DevTN
DevTN

Reputation: 593

how to loop through array with dynamic keys in PHP

I have an array data where I am storing the result of an SQL query as below :

$stmt = sqlsrv_query($db,$sql);  
$data = [];
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
if(!empty($row)) { $data[] = $row; }  }

then I want to create a group key which is the concatenation of specific keys of my array data as below :

foreach ($data as $d) {

$group_key = $d['id'].'_'.$d['Country'].'_'.$d['Order Numer']; 

//rest of my code 

}

it works fine but I want to choose the keys dynamically instead of setting up manually id, Country and Order Number... let's say I have an array $PostKeys = ["id","Country","Order Number"]; this array will vary depending on the values selected by user...

What I did is :

$PostKeys = ["id","Country","Order Number"];

foreach ($data as $d) { 

  foreach($PostKeys as $value)
  { $array_group_key[] = $d[$value] ; }

$group_key = implode("_",$array_group_key); 
// rest of my code 
}

I am supposed to get the same result but there is always mismatch. I didn't figure out where is the issue exactly. Any suggestions please ? Thank you very much.

Upvotes: 0

Views: 877

Answers (1)

Barmar
Barmar

Reputation: 780889

You need to empty $array_group_key each time through the loop. Otherwise, you're appending to the results from all the previous rows.

foreach ($data as $d) { 
    $array_group_key = [];
    foreach($PostKeys as $value)
    { 
        $array_group_key[] = $d[$value] ; 
    }
}

Upvotes: 1

Related Questions