如何在PHP中使用多维数组中的键创建数组

时间:2012-07-03 04:29:30

标签: php arrays

以下数组存储在$this->config->item('userlib_profile_fields')

Array
(
[0] => Array
    (
        [first_name] => First Name
    )
[1] => Array
    (
        [family_name] => Family name
    )
[2] => Array
    (
        [web_address] => Web Address
    )
[3] => Array
    (
        [company_name] => Company Name
    )
...
...
)

我想从上面的键创建一个数组。

Array(first_name, family_name, web_address,company_name, .....)

我尝试了这个,但它给出了错误。

$profile_columns = array();
foreach($this->config->item('userlib_profile_fields') as $value)
{
    foreach($value as $key=>$value)
    {
        //var_dump ($key);
        $profile_columns = array_push($profile_columns,$key);
    }
}
// error: array_push() expects parameter 1 to be array, integer given
array_push() expects parameter 1 to be array, null given

4 个答案:

答案 0 :(得分:1)

复制你的数组的示例。

$array = array(
    array('first_name' => 'First Name'),
    array('family_name' => 'Family Name'),
    array('web_address' => 'Web Address'),
    array('company_name' => 'Company Name')
);

循环和提取。 (保留数组键)

$items = array();
foreach($array as $item) {
    foreach($item as $key => $value) {
        $items[$key] = $value;
    }
}

这将输出

Array
(
    [first_name] => First Name
    [family_name] => Family Name
    [web_address] => Web Address
    [company_name] => Company Name
)

如果要将数组键重置为索引数组,请使用此方法。

$items = array();
foreach($array as $item) {
    foreach($item as $key => $value) {
        $items[] = $value;
    }
}

这将输出

Array
(
    [0] => First Name
    [1] => Family Name
    [2] => Web Address
    [3] => Company Name
)

答案 1 :(得分:0)

更改$profile_columns = array_push($profile_columns,$key);
array_push($profile_columns,$value); $profile_columns[] = $value;

答案 2 :(得分:0)

$test = array
(
array  (        'first_name' => 'First Name'    ),
array  (        'family_name' => 'Family name'  ),
array  (        'web_address' => 'Web Address'    ),
array  (        'company_name' => 'Company Name'    )
); 

$items = array();
for($i = 0 ; $i < count($test) ; $i++) {
    array_push($items,$test[$i][key($test[$i])]);
} 
print_r($items);

将输出如下:

Array ( [0] => First Name [1] => Family name [2] => Web Address [3] => Company Name )

答案 3 :(得分:0)

    <?php
    $test = array
    (
    array  (        'first_name' => 'First Name'    ),
    array  (        'family_name' => 'Family name'  ),
    array  (        'web_address' => 'Web Address'    ),
    array  (        'company_name' => 'Company Name'    )
    );

$items = array();

for($i = 0 ; $i < count($test) ; $i++) {

array_push($items,$test[$i][key($test[$i])]);

}