【问题标题】:a better way to convert an array to an object将数组转换为对象的更好方法
【发布时间】:2019-02-26 10:23:56
【问题描述】:

有如下数组,

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

我需要将它转换成这个stdClass 对象

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

为了做到这一点,我使用这些嵌套的foreach

$object = new stdClass;

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

// At this point $object is the expected output

我正在寻找一种更好的方法来避免 foreach 嵌套

最终的预期输出是

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

感谢您的建议。

【问题讨论】:

  • $arr = ['a' => 10]; (object) $arr

标签: php


【解决方案1】:

检查一下!它工作正常

首先是array_merge,然后是json_encode,然后是json_decode 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);

您也可以将object 用于stdClass 之类的

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

有多种方法可以获取stdClass object。所以,here is the most valuable answer for stdClass object

【讨论】:

  • 非常好...我从 json_decode/encode 嵌套路径开始,但没有先合并数组
【解决方案2】:

抱歉,我错过了您想要展平阵列的位置。我将添加 Bilal Ahmed 合并数组的建议。

对于您的案例示例,您不需要使用json_decode(json_encode($dataset));

但是,请记住,如果您有嵌套数组,json_decode(json_encode($dataset)); 是更好的解决方案。

$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>';

这将输出:

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

【讨论】:

  • 感谢您的回答,但我没有得到预期的输出
  • 您是否期待 json 输出。
  • 没有得到预期的答案
【解决方案3】:

我相信这将是完成这项工作的一种优雅方式

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

print_r($dataset);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-06
    • 2017-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-03
    • 2021-04-21
    相关资源
    最近更新 更多