PHP按类别转换数组,只有一个标题

时间:2013-10-01 03:34:33

标签: php arrays

我有这个数组:

$result = array(
    '0' => array(
        'field_categories' => 'Visitor', 
        'field_name' => 'Visitor-1', 
    ), 
    '1' => array(
        'field_categories' => 'Visitor', 
        'field_name' => 'Visitor-2'
    ), 
    '2' => array(
        'field_categories' => 'Visitor', 
        'field_name' => 'Visitor-3'
    ), 
    '3' => array(
        'field_categories' => 'Visitor', 
        'field_name' => 'Visitor-4'
    ), 
    '4' => array(
        'field_categories' => 'Doctor', 
        'field_name' => 'Doctor-1'
    ), 
    '5' => array(
        'field_categories' => 'Doctor', 
        'field_name' => 'Doctor-2'
    ), 
    '6' => array(
        'field_categories' => 'Manager', 
        'field_name' => 'Manager-1'
    ), 
    '7' => array(
        'field_categories' => 'Manager', 
        'field_name' => 'Manager-2'
    ), 
    '8' => array(
        'field_categories' => 'Manager', 
        'field_name' => 'Manager-3'
    )
);
echo '<pre>',print_r($result),'</pre>';

如何将其转换为此格式? (echo '<pre>',print_r($result),'</pre>';的输出)谢谢

Array
(
    [0] => Visitor
    [1] => Visitor-1
    [2] => Visitor-2
    [3] => Visitor-3
    [4] => Visitor-4
    [5] => Doctor
    [6] => Doctor-1
    [7] => Doctor-2
    [8] => Manager
    [9] => Manager-1
    [10] => Manager-2
    [11] => Manager-3
)

3 个答案:

答案 0 :(得分:2)

$result = array(
    '0' => array(
        'field_categories' => 'Visitor', 
        'field_name' => 'Visitor-1', 
    ), 
    '1' => array(
        'field_categories' => 'Visitor', 
        'field_name' => 'Visitor-2'
    ), 
    '2' => array(
        'field_categories' => 'Visitor', 
        'field_name' => 'Visitor-3'
    ), 
    '3' => array(
        'field_categories' => 'Visitor', 
        'field_name' => 'Visitor-4'
    ), 
    '4' => array(
        'field_categories' => 'Doctor', 
        'field_name' => 'Doctor-1'
    ), 
    '5' => array(
        'field_categories' => 'Doctor', 
        'field_name' => 'Doctor-2'
    ) );

 foreach($result as $key=>$val)
    {
      $newarray[$val['field_categories']][] = $val['field_name'];
    }

print_r( $newarray);

<强>输出

Array
(
    [Visitor] => Array
        (
            [0] => Visitor-1
            [1] => Visitor-2
            [2] => Visitor-3
            [3] => Visitor-4
        )

    [Doctor] => Array
        (
            [0] => Doctor-1
            [1] => Doctor-2
        )

)

答案 1 :(得分:1)

只需在echo语句之前添加此行:

$result = array_map(function($e){return isset($e['field_name'])?$e['field_name']:null;} , $result);

答案 2 :(得分:0)

如果您要尝试重复field_namefield_categories,可以将每个值分配给数组的键,然后执行array_flip

$new_result = array();
$i = 0;
foreach($result as $res){
    $new_result[$res["field_name"]] = $i;
    $new_result[$res["field_categories"]] = $i+1;
    $i += 2;
}

$new_result = array_flip($new_result);