重新排列php数组结构

时间:2014-06-19 10:18:34

标签: php mysql arrays loops foreach

是否有任何简单的解决方案可以使用php或任何方法转换mysql foreach结果更改数组结构?

当前结果

Array
(
    [1033] => stdClass Object
        (
            [id] => 1033
            [plugin] => kooyke
            [name] => kooyduration
            [value] => 13
        )

    [1029] => stdClass Object
        (
            [id] => 1029
            [plugin] => kooyke
            [name] => kooyendpoint
            [value] => http://localhost/public/data/
        )

    [1030] => stdClass Object
        (
            [id] => 1030
            [plugin] => kooyke
            [name] => kooylogin
            [value] => ryrtrtr68fds876fdsf876fsd87fd
        )
)

期待结果

Array
(
    [kooyduration] => 13
    [kooyendpoint] => http://localhost/public/data/
    [kooylogin] => ryrtrtr68fds876fdsf876fsd87fd
)

尝试转换的代码

foreach($result as $value){
  $expresult[] = $value['value'];
}
print_r($expresult);

2 个答案:

答案 0 :(得分:2)

Bellow代码块可以帮助您。

$i = 0;
$last_arr = array();
$new_arr = array();
foreach($my_array as $key=>$val)
{
   $new_arr[$val->name] = $val->value;
}
array_push($last_arr,$new_arr);

答案 1 :(得分:1)

您不能使用$value['value'],因为对象应该是$value->value。并将新数组推送到name索引。请尝试以下方法:

$expresult = array();

foreach($result as $value)
{
  $expresult[$value->name] = $value->value;
}