a little silly question.

I am trying to fill the array with a sample of the database in the following way:

foreach ($sql_student as $key) { $students = array($k => array("name" => $key['name'],"id" => $key['id'])); $k++; } 

$ sql_student contains the following:

 array(3) { [0]=> array(3) { ["id"]=> string(2) "15" ["name"]=> string(44) "Иванов" ["groupp"]=> string(1) "5" } [1]=> array(3) { ["id"]=> string(2) "18" ["name"]=> string(8) "Кекк" ["groupp"]=> string(1) "5" } [2]=> array(3) { ["id"]=> string(2) "19" ["name"]=> string(6) "лал" ["groupp"]=> string(1) "5" } } 

accordingly, when writing to the $ students array, each time it is overwritten and only the last entry remains. Already the eyes do not see where I did wrong. Help me please:)

  • $ students [] = ["name" => $ key ['name'], "id" => $ key ['id']]; - tcpack4
  • @ tcpack4 create an answer, I mark your answer correct. Thanks you! - sbaikov
  • option - $students = array_map(function($v){ unset($v['groupp']); return $v;}, $sql_student); but do you really need to do almost a clone of the array? one field less, one more, unless you serialize it somewhere. - teran
  • @teran yes, for serialization once again - sbaikov

1 answer 1

You re-create the array at each step. Initialize an empty array before the loop. Actually something like this:

 $students = []; foreach ($sql_student as $key) { $students[$k] = [ "name" = $key['name'], "id" = $key['id'] ]; $k++; }