diegoaguilar
diegoaguilar

Reputation: 8376

Adding key-value in PHP array?

Inside a loop where I'm dealing with variables related to a product and a number of units, I'm trying to add these two to an array:

$pedido = array();

So,

    foreach($_POST as $post_key => $post_value){

        if ($post_value=="on") {
            $nombreProducto = mysql_fetch_assoc($mySQL->query("SELECT nombre from productos WHERE id_producto='$post_key'"));
            $cantidad = $_POST[$post_key."Number"];

            echo "<h1>".$nombreProducto['nombre']."</h1>"." Cantidad: ".$cantidad." <br><br>";
            $pedido["$nombreProducto"] = $cantidad;
        }
    }

It's right in:

$pedido["$nombreProducto"] = $cantidad;

Where I try to perform the adding, however the output of var_dump is like:

array(1) { ["Array"]=> string(1) "3" }

Not exactly what I wanted neither the format.

Upvotes: 1

Views: 78

Answers (4)

Horse SMith
Horse SMith

Reputation: 1035

The following makes no sense to do:

$pedido["$nombreProducto"] = $cantidad;

What are you trying to do here? I think what you want to do is this:

$pedido[$nombreProducto['nombre']] = $cantidad;

Also you may want to try to output the array like this:

print_r($pedido);

I recommend you re-write the mysql query so you don't need to loop it. That is for safety and efficiency reasons. I also recommend you use mysqli instead of mysql, because mysql is deprecated and unsafe to use. You don't check if $_POST[$post_key."Number"] is set, at least not in this code. I hope you sanitize/validate the input from $_POST before using it against the database?

Upvotes: 0

redelschaap
redelschaap

Reputation: 2814

Use $pedido[$nombreProducto['nombre']] = $cantidad; instead of $pedido["$nombreProducto"] = $cantidad;

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

You shouldn't be putting a variable by itself in quotes. Remove the quotes.

Also, since you were just accessing $nombreProducto['nombre'] on the previous line, it's fairly obvious that that variable is an array. You cannot use an array as a key, only integers and strings are allowed. So use something that identifies it, such as its ID number.

Upvotes: 1

Sal00m
Sal00m

Reputation: 2916

Remove quotes and

$pedido[$nombreProducto['nombre']] = $cantidad;

EDITED

It seems $nombreProducto is an array so you need to indicate the key field, so i changed to use the field "nombre"

If you see your var_dump it's an Array with the key "Array" this is why you are trying to convert the array to string and it return the word "Array"

Upvotes: 1

Related Questions