Smylif3
Smylif3

Reputation: 33

Get the values of an associaive array [PHP]

How can i get the values of the array bellow?

     Array
(
    [list_items] => Array
        (
            [0] => Array
                (
                    [productName] => BUGGY INFANTIL PRO 125CC
                    [productId] => 1
                    [productColor] => Azul
                    [productQuantity] => 2
                    [productIMG] => http://localhost/kasi_src/img/vehicules/buggygasolina/BUGGY-INFANTIL-125CC-AZUL.png
                    [productURL] => http://localhost/kasi_src/125CCInfantil.html
                    [productPrice] => 1000
                )

            [1] => Array
                (
                    [productName] => PATINETE 24V
                    [productId] => 2
                    [productColor] => Azul
                    [productQuantity] => 2
                    [productIMG] => http://localhost/kasi_src/img/vehicules/patinetes/24.png
                    [productURL] => http://localhost/kasi_src/patinete-24v.html
                    [productPrice] => 240
                )

        )

)

I tried a simple foreach loop

foreach($items as $key => $value){
  echo  $value . "\n";      
        }

but i ended up getting this error : Notice: Array to string conversion in ..... Any ideas ?

Upvotes: 1

Views: 40

Answers (2)

Fabio Crispino
Fabio Crispino

Reputation: 731

Use var_export($obj,true) if you want to get a textual representation of the full content of each array associated to a key in an associative array as in the example, or simply access the keys of each subarray to retrieve individual values as productName.

<?php
$list_items = array(
    0 => array("productName" => "Marshmallows"),
    1 => array("productName" => "Mikado"),
);

foreach($list_items as $key=>$obj){
    echo var_export($obj,true)."<br/>";
    // Or access each array key, for example: echo $obj['productName'];
}
?>

Output:

array ( 'productName' => 'Marshmallows', )
array ( 'productName' => 'Mikado', )

Upvotes: 0

LF-DevJourney
LF-DevJourney

Reputation: 28529

You cannot echo a array.

    foreach($array["list_items"] as $list_item){
        echo $list_item["productName"];
    }

Upvotes: 1

Related Questions