简体   繁体   English

将stdClass对象转换为php中的关联数组

[英]Convert stdClass object to associative array in php

I need to convert this array我需要转换这个数组

Array ( 
[0] => stdClass Object 
     ( [title] => primo ) 
[1] => stdClass Object 
     ( [title] => secondo )) 

to

Array ( 
[primo] => primo
[secondo] => secondo ) 

Tried different options, including typecast, still not found the correct solution尝试了不同的选项,包括类型转换,仍然没有找到正确的解决方案

Use json_encode() and json_decode()使用json_encode()json_decode()

$arr = json_decode(json_encode($yourObject), TRUE);

json_decode() 's second parameter is set to TRUE . json_decode() 的第二个参数设置为TRUE

Function definition:函数定义:

mixed json_decode ( string $json [, bool $assoc = false [, int $depth > = 512 [, int $options = 0 ]]] )混合 json_decode ( string $json [, bool $assoc = false [, int $depth > = 512 [, int $options = 0 ]]] )

That will convert your object into an associative array.这会将您的对象转换为关联数组。

Finally I did it this:最后我这样做了:

$options = array('' => '<select>');
$results = $query->execute()->fetchAll();
foreach($results as $id => $node) {
  $value = $node->title;
  $options[$value] = $value;
}

Thanks for all your answer谢谢大家的回答

Check this code please, I haven't debugged it...请检查此代码,我还没有调试它...

$array = array_values($array);
$new_array = array();
foreach($array as $row){
   $new_array[$row['title']] = $row['title'];
}
$final_array = array();

foreach ($items as $item)
{
    $final_array = array_merge($final_array, json_decode(json_encode($item), true);
}

Where $items is the name of your array. $items是数组的名称。 Should go through your array of objects, convert that object to an associative array, and merge it into the $final_array应该遍历您的对象数组,将该对象转换为关联数组,并将其合并到$final_array

Simply use array_walk like as只需像这样使用array_walk

$result = array();
array_walk($arr,function($v)use(&$result){ 
      $result[$v->title] = $v->title;
});
print_r($result);

To blindly answer the title of the thread, you can achieve object conversion to an associative array by simply casting it:盲目回答题主,可以通过简单的强制转换来实现对象到关联数组的转换:

$array = (array) $object;

However, in the discussed example, rudimentary operations can help generate the desired data structure without using any built-in function:但是,在讨论的示例中,基本操作可以帮助生成所需的数据结构,而无需使用任何内置函数:

$array = [];
foreach ($arrayOfObjects as $object) {
    $title = $object->title ?? null;
    if (!is_null($title)) {
        $array[$title] = $title;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM