如何在php中将对象数组转换为嵌套数组

时间:2018-01-03 23:18:01

标签: php arrays

我有一个这样的数组:

array(4) { 
    [0]=> object(stdClass)#19 (3) { ["column_name"]=> "article_id" 
    ["caption"]=> "Article Id" ["input_type"]=> "Number" }

    [1]=> object(stdClass)#21 (3) { ["column_name"]=> "issue_date" 
    ["caption"]=> "Issue Date" ["input_type"]=> "Date" } 

    [2]=> object(stdClass)#22 (3) { ["column_name"]=> "title" 
    ["caption"]=> "Title" ["input_type"]=> "Text" }
}

如何将其转换为如下数组:

array(){
    ["column_name"]=> array('article_id', 'issue_date', 'title')
}

2 个答案:

答案 0 :(得分:0)

您可以循环然后将每个column_name推送到新数组

$result = [];
foreach ($array as $obj) {
    $result[] = $obj->column_name;
}

print_r($result);

答案 1 :(得分:0)

这应该可以解决问题:

<?php

// Create Data

$data = array();

$object1 = new stdClass();
$object1->column_name = 'article_id';
$object1->caption = 'Article Id';
$object1->input_type = 'Number';
$data[0] = $object1;

$object2 = new stdClass();
$object2->column_name = 'issue_date';
$object2->caption = 'Issue Date';
$object2->input_type = 'Date';
$data[1] = $object2;

$object3 = new stdClass();
$object3->column_name = 'title';
$object3->caption = 'Title';
$object3->input_type = 'Text';
$data[2] = $object3;

print_r($data);

// Parse Data

$col_names = array();

foreach ($data as $object) {
    $col_names[] = $object->column_name;
}

print_r($col_names);

?>

访问this link尝试一个有效的演示。