Home > database >  illegal offset type in php on vscode no error, but on page says that error
illegal offset type in php on vscode no error, but on page says that error

Time:06-30

hello i'm running into a problem, it says on the browser illegal offset type, im declaring an array this way:

 $matriculas = [
        1 => ["99-99-99", "D"],
        2 => ["88-88-88", "D"],
    ];

and the error is in this line :

 $series[$option] = [$option['matricula'],$option['type']];

the function looks like this:

<?php 
    $query ="SELECT * FROM matriculas";
    $result = $con->query($query);
    if($result->num_rows> 0){
      $options= mysqli_fetch_all($result, MYSQLI_ASSOC);
    }
    $series = array();
    foreach ($options as $option) {
        $series[$option] = [$option['matricula'],$option['type']];
    }
?>
<select name="id">
   <option>Select matricula</option>
<?php 
  foreach ($series as $ID => $values) {
?>
    <option name=<?php $ID ?> > <?php echo $values[0]; ?></option>
<?php 
}
>
</select>

how can i make it right? thanks in advance for your help

CodePudding user response:

It's almost right.

Based on the subsequent foreach ($series as $ID => $values), I think you want this instead:

foreach ($options as $option) {
    $series[$option['id']] = [$option['matricula'], $option['type']];
}

But unless you're going to use the $option['type'] value for something else later, it could be simplified to

foreach ($options as $option) {
    $series[$option['id']] = $option['matricula'];
}

CodePudding user response:

Option in your case is an array and you cannot make an array the key of the index. So instead of $series[$option] you should do $series[$option['matricula']] or $series[$option['type']] as its a single value.

CodePudding user response:

instead of that why you don't modify this to fit? so then where you have foreach ($series as $ID => $values) { to replace that with echo $sum; so try to modify the piece in this way (you may modify it in case isn't work but the idea is to not fill the memory with a new array but what you read already to sum it and output text as template insertion)

$sum='';
$series = array();
    foreach ($options as $option) {
        //nope! $series[$option] = [$option['matricula'],$option['type']];
$sum.=<<<opt

 <option name="{$option['matricula']}">{$option['type']}</option>
opt;
 }
  •  Tags:  
  • php
  • Related