0

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.

0

4 Answers 4

3

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' ); 
Sign up to request clarification or add additional context in comments.

1 Comment

ok i've tryed that and it works but how to get to that result, i have an ajax call that goes to a controller in the controller i need to encode that code it's very simple but the question is should i do it in a foreach loop? i mean how to make that multidimensional array . Each time i add a new product that products array should be like '$arr = array( 'products' => array( array('id'=>4, link => 'product.php?id_product=4' ), array('id'=>5, link => 'product.php?id_product=5' ) ) ); '
0
$data = array( 'products' => array( array('id'=>5, link => 'product.php?id_product=5' ... and so on), array('id'=>5, link => 'product.php?id_product=5' ... and so on) // repeat once for element. ) ); json_encode($data); 

Comments

0

If you need to return an AJAX responce in JSON format - you need to add a header.

<?php header("Content-type: application/json"); echo json_encode($array); 

Otherwise - you can print the array into a JS global variable.

<?php echo '<script>'; echo 'var foo = ' . json_encode($array); . ';'; echo '</script>'; 

Comments

0

That is the output of json_encode($array), where $array is nested.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.