Alex Marius Alex Marius - 7 months ago 11
PHP Question

PHP array format

How can I get this format:

{
"products": [
{
"id": 4,
"link": "/product.php?id_product=4",
"quantity": 1,
"priceByLine": "$185.00",
"name": "Orci hendrer...",
"price": "$185.00",
"idCombination": 0,
"hasAttributes": false,
"hasCustomizedDatas": false,

"customizedDatas":[
]


}, {
"id": 5,
"link": "/product.php?id_product=5",
"quantity": 1,
"priceByLine": "$215.00",
"name": "Semper rutru...",
"price": "$215.00",
"idCombination": 0,
"hasAttributes": false,
"hasCustomizedDatas": false,

"customizedDatas":[
]


}],

}


as a PHP array? I've tried

$array[] = array('id'=>5, link => 'product.php?id_product=5' ... and so on)


but when I encode with JSON it doesn't work.

Answer

You just have to nest your arrays in the proper way like the following example.

$arr = array( 'products' => array(
  array('id'=>4, link => 'product.php?id_product=4' ),
  array('id'=>5, link => 'product.php?id_product=5' )
  )
);

EDIT

In your code it would look like this to init the object:

$arr = array( 'products' => array() );

And each subsequent product could be added like this (e.g., in a loop where you parse your database result):

$arr['products'][] = array('id'=>5, link => 'product.php?id_product=5' );