1

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

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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);

P.S By the way, php supports associative arrays. So, that`s not an object, it is an associative array (array with keys)

[
 [
   'key' => 'value'
 ] 
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.