Louis Lee
Louis Lee

Reputation: 281

PHP - object array into json

array of $setting['accountType'] :

$setting['accountType']['all'] = 'ALL';
$setting['accountType']['A1'] = 'VIP1';
$setting['accountType']['A2'] = 'VIP2';

PHP code to generate the object:

$object = new stdClass();
    $myArray = array();
    foreach ($setting['accountType'] as $key => $val)
    {                       
        $object->id = $key;
        $object->desc = $val;
        $myArray[] = $object;       
    }
    $accountType = $myArray;

PHP code to format object into json:

json_encode(['accountType'=> [(object)$accountType]));

However, i get the output as below :

"accountType": [{
    "0": {
        "id": "A2",
        "desc": "VIP"
    },
    "1": {
        "id": "A2",
        "desc": "VIP"
    },
    "2": {
        "id": "A2",
        "desc": "VIP"
    }
}]

Problem 1: why $accountType only keep the last object when I loop through?

Problem 2: without the array key of $accountType [solved by using array_values($accountType)]

This is something that I am trying to achieve:

"accountType": [{
        "id": "all",
        "desc": "All "
    }, {
        "id": "A1",
        "desc": "Normal"
    }, {
        "id": "A2",
        "desc": "VIP"
    }]

How to get the output as above?

Upvotes: 2

Views: 62

Answers (3)

bansi
bansi

Reputation: 56982

You should use

json_encode(['accountType'=> $accountType]);

instead of

json_encode(['accountType'=> [(object)$accountType]]);

In your code you are putting $accountType inside another array that is why you are getting that result

Here is a Demo and Explanation

Edit: The entire code

$setting['accountType']['all'] = 'ALL';
$setting['accountType']['A1'] = 'VIP1';
$setting['accountType']['A2'] = 'VIP2';

$myArray = array();
foreach ($setting['accountType'] as $key => $val)
{                       
    $object = new stdClass(); // Note: $object should be created inside the loop
    $object->id = $key;
    $object->desc = $val;
    $myArray[] = $object;       
}
$accountType = $myArray;
echo json_encode(['accountType'=> $accountType]);

And Here is the Revised Demo

Upvotes: 1

Banana
Banana

Reputation: 91

This is exactly the same thing, no? The numerotation is displayed because you need it to access to the specific json object. You have an array and you can access to each element by its key.

Upvotes: 0

Rahul
Rahul

Reputation: 18557

Try this,

echo json_encode(array_values($your_array));

Let me know if its working

Upvotes: 1

Related Questions