0

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.

3
  • What is the value of $PostKeys? What result do you get? Are you resetting $array_group_key before each sub-loop? Also, please reformat your code properly. Commented Mar 24, 2020 at 21:30
  • @Jeto I formatted my code. I hope it's more clear now. Commented Mar 24, 2020 at 21:37
  • Thanks, but not really, you should refer to php-fig.org/psr/psr-12/#example for a good example of what most PHP projects follow. What about my other questions? Commented Mar 24, 2020 at 21:41

1 Answer 1

1

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] ; 
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.