1

I have an array fetched from mysql.

while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
    $array[] = $row;
}
var_dump($array);

It returns the values as below:

array (size=2)
  0 => 
    array (size=4)
      'itemId' => string '4' (length=1)
      'name' => string 'Ice Break' (length=9)
      'size' => string '500ml' (length=5)
      'supplier' => string 'Parmalat' (length=9)
  1 => 
    array (size=4)
      'itemId' => string '6' (length=1)
      'name' => string 'Red bull' (length=9)
      'size' => string '250ml' (length=5)
      'supplier' => string 'Red Bull' (length=9)

Now, I want to add a customised key and value to this array so that the result is as below:

array (size=2)
  0 => 
    array (size=5)
      'itemId' => string '4' (length=1)
      'name' => string 'Ice Break' (length=9)
      'size' => string '500ml' (length=5)
      'supplier' => string 'Parmalat' (length=8)
      'newName' => string 'Ice Break (500ml) (Parmalat)' (length=28)
  1 => 
    array (size=5)
      'itemId' => string '6' (length=1)
      'name' => string 'Red Bull' (length=8)
      'size' => string '250ml' (length=5)
      'supplier' => string 'Red Bull' (length=8)
      'newName' => string 'Red bull (250ml) (Red Bull)' (length=26)

I have tried this so far, but no luck:

while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
        $array[] = $row;
        $array['newName'] = $row["name"].' ('.$row["size"].') ('.$row["supplier"].')';
    }

1 Answer 1

1

You're close. Add it to $row and then append it to the array.

while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
    $row['newName'] = $row["name"].' ('.$row["size"].') ('.$row["supplier"].')';
    $array[] = $row;
}
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.