Home > Net >  Convert array to object in php - Convert this array to object in php
Convert array to object in php - Convert this array to object in php

Time:12-09

Help me convert this array to object in php, below is my code

data: [
    [
        1638849672000,
        0.0025
    ],
    [
        1638849732000,
        0.0008
    ],
    [
        1638849792000,
        0
    ],
    [
        1638849852000,
        0
    ]
]

I want convert to Object

data: [
    {
        'time': 1638849670000,
        'value': 0.0025,
    },
    {
        'time': 1638849730000,
        'value': 0.0008,
    },
    {
        'time': 1638849790000,
        'value': 0.0,
    },
    {
        'time': 1638849850000,
        'value: 0.0,
    }
]

Here is my code

$newdata = [];
foreach ($data as $key => $value) {
    foreach ($value as $vl) {
        array_push($newdata, [
            'time' => $vl,
            'value' => $vl
        ]);
    }
}

Help me convert this array to object in php, below is my code Thank you very much

CodePudding user response:

Basically you can just cast your array in object

$newData = (object) $data;

Or use the stdClass

$newData = new stdClass();
foreach ($data as $key => $value)
{
    $newData->$key = $value;
}

https://www.php.net/manual/fr/language.types.object.php#language.types.object.casting

CodePudding user response:

If you want an array of objects, you could use array_map:

$data = array_map(function($x) {
    return (object)[
        "time" => $x[0],
        "value" => $x[1]
    ];
}, $data);

PHP demo

CodePudding user response:

You extremely don`t need nested foreach. You can use amazing built-in php function such as array_combine().

There are 3 options how to do that (can be more if you are creative person :D)

$keys = ['time', 'value'];

/** 1 option */
foreach($data as $value){
    $newData[] = array_combine($keys, $value);
}

/** 2 option */
foreach($data as $key => $value){
    $data[$key] = array_combine($keys, $value);
}


/** 3 option */
$newData2 = array_map(function($value) use ($keys){
    return array_combine($keys, $value);
}, $data);
  • Related