Yves Gonzaga Yves Gonzaga - 3 years ago 158
PHP Question

Creating a json with array inside PHP?

I tried to implement it something like this

private static function getData($datas) {

$days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
$days_aliases = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'];

$open_rates = array();

foreach ($datas as $data) {

$date = Carbon::parse($data->created_at)->format('l');

for($i = 0; $i < count($days); $i++) {

if($date == $days[$i]){

$open_rates['x'][$i] = $days_aliases[$i];
$open_rates[$data->name][$i] = (int)$data->open_rate;

}

}

}

return $open_rates;

}


But the result is like this.

{
"x": {
"0": "SUN",
"1": "MON",
"2": "TUE",
"3": "WED",
"4": "THU",
"5": "FRI",
"6": "SAT"
}
}

How to make an array like this PHP?

json: {
'Day Pass' : [40, 10, 99, 50],
'Day Pass' : [40, 10, 99, 50],
'Day Pass' : [40, 10, 99, 50],
'Day Pass' : [40, 10, 99, 50],
'Day Pass' : [40, 10, 99, 50]
}

Answer Source

Simply create a numeric-indexed array. Note that you can't have multiple keys with the same name in an array, so you need different names for "Day pass", otherwise you'd be overwriting them:

<?php
$json = [
    "json" => [
        "Day pass" => 
            [40, 10, 99, 50],
        "Day pass2" => 
            [40, 10, 99, 50],
        "Day pass3" => 
            [40, 10, 99, 50],
        "Day pass4" => 
            [40, 10, 99, 50],
    ],
];
print_r(json_encode($json));

Gives the correct result:

{
    "json": {
        "Day pass": [40, 10, 99, 50],
        "Day pass2": [40, 10, 99, 50],
        "Day pass3": [40, 10, 99, 50],
        "Day pass4": [40, 10, 99, 50]
    }
}

Demo

Using the same key instead, gives you one item:

<?php
$json = [
    "json" => [
        "Day pass" => 
            [40, 10, 99, 50],
        "Day pass" => 
            [40, 10, 99, 50],
        "Day pass" => 
            [40, 10, 99, 50],
        "Day pass" => 
            [40, 10, 99, 50],
    ],
];
print_r(json_encode($json));

Result:

{
    "json": {
        "Day pass": [40, 10, 99, 50]
    }
}

Demo


The problem with your specific code is that, in order to have json_encode() return a JSON array (instead of an object), the PHP array needs to be a numeric sequential 0-indexed array. What you can do is pass the array through array_values() in order to only preserve the values and reset the keys:

<?php
$open_rates = [];
$open_rates["x"]["0"] = "Sun";
$open_rates["x"]["2"] = "Mon";
var_dump(json_encode($open_rates)); // JSON object
$open_rates["x"] = array_values($open_rates["x"]);
var_dump(json_encode($open_rates)); // JSON array

Demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download