Skip to content
Advertisement

Removing a key from a nested array in php

I am trying to display information taken from a mysql database but i do not want to display the ‘id’ field in the results. i got the displaying part down just fine. just need to remove a field from the view.

$plantarray = array();
if($result = $mysqli->query($hoyaquery)){
    if(mysqli_num_rows($result) > 0){
        while($row = mysqli_fetch_assoc($result)){
            $plantarray[] = $row;
        }
    } 
}

The code will return a nested array of results but it includes the tables id field.

its then displayed using:

<?php if (count($plantarray) > 0): ?>
<table>
  <thead>
    <tr>
      <th><?php echo implode('</th><th>', array_keys(current($plantarray))); ?></th>
    </tr>
  </thead>
  <tbody>
<?php foreach ($plantarray as $row): array_map('htmlentities', $row); ?>
    <tr>
      <td><?php echo implode('</td><td>', $row); ?></td>
    </tr>
<?php endforeach; ?>
  </tbody>
</table>
<?php endif; ?>

ive tried to loop through the outside array and target the key ‘id’ but it doesnt do anything at all if i unset the id.

foreach($plantarray as $key){
  unset($key['id']);
}

this does nothing at all.

i know the problem is in the looping, because if i set an array with the same data and i unset[‘id’] then it removes the id.

$p = [ "id" => 3, "Family" => "Apocynaceae", "Genus" => "Hoya", "Species" => "curt" ];
unset($p["id"]);
print_r($p);

i could have this completely wrong. I’m not sure. I’m unsure where its going wrong.

Advertisement

Answer

The reason that your loop doesn’t work is because you aren’t unsetting the values in the array itself, rather in the “copy” that is generated during the foreach loop. If you want to use this solution then the right code looks something like this:

foreach($plantarray as &$key){
  unset($key['id']);
}

The & symbol will pass the row by reference which will make your manipulations be kept in the original array.

That said, this is not a performant way of doing this. Ostensibly, you have a query somewhere above this code that looks something like

$hoyaquery = "SELECT * FROM plant-table-name";

Instead, just don’t get the id column from the database at all.

$hoyaquery = "SELECT Family, Genus, Species FROM plant-table-name"

That will prevent you from needing to loop through all your results in the first place.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement