0

Having the following array,

$dataset = [
    ['item1' => 'value1'],
    ['item2' => 'value2'],
    ['item3' => 'value3'],
];

I need to convert it to this stdClass object

$dataset = [
    'item1' => 'value1',
    'item2' => 'value2',
    'item3' => 'value3',
];

In order to do that, I use these nested foreach

$object = new stdClass;

foreach ($dataset as $item) {
    foreach ($item as $key => $value) {
        $object->{$key} = $value;
    }
}

// At this point $object is the expected output

I look for a better way to do it, one in which I can avoid foreach nesting

The final expected output is

stdClass Object
(
    [item1] => value1
    [item2] => value2
    [item3] => value3
)

Thanks for your suggestions.

Abhishek
  • 539
  • 5
  • 25
Mario
  • 4,784
  • 3
  • 34
  • 50

3 Answers3

3

check this! it's working fine

first array_merge and then json_encode and json_decode for stdClass

<?php
$dataset = [
    ['item1' => 'value1'],
    ['item2' => 'value2'],
    ['item3' => 'value3'],
];


$dataset = call_user_func_array('array_merge', $dataset);
$dataset= json_decode(json_encode($dataset));
echo "<pre>";
print_r($dataset);

and also you can used object for stdClass like

$dataset=(object) $dataset;//make sure first you merge array

there is a multiple way to get stdClass object. So, here is the most valuable answer for stdClass object

Bilal Ahmed
  • 4,005
  • 3
  • 22
  • 42
  • 1
    very nice... I started down the json_decode/encode nesting path, but didn't merge the array first – ivanivan Sep 22 '18 at 04:27
1

Sorry, I missed where you wanted to flatten the array. I will add Bilal Ahmed suggestion for merging the arrays.

For your case example you do not need to use the json_decode(json_encode($dataset));

However, keep in mind that json_decode(json_encode($dataset)); is the better solution if you have nested arrays.

$dataset = [
    ['item1' => 'value1'],
    ['item2' => 'value2'],
    ['item3' => 'value3'],
];

$dataset = call_user_func_array('array_merge', $dataset);    
$object = (object)$dataset;

echo '<pre>';
print_r($object);
echo '</pre>';

This will output:

stdClass Object
(
    [item1] => value1
    [item2] => value2
    [item3] => value3
)
Joseph_J
  • 3,654
  • 2
  • 13
  • 22
0

I believe this will be an elegant way to do the job

$dataset = (object)call_user_func_array('array_merge', $dataset);

print_r($dataset);
Rinsad Ahmed
  • 1,877
  • 1
  • 10
  • 28