在数组的内部如果缺少索引,则为缺少的索引添加空索引

时间:2018-09-28 12:57:41

标签: php arrays multidimensional-array

//这是数组,下面是我想要的

$data = array(
    array(
            'title' => 'My title',
            'date' => 'My date'
    ),
    array(
            'title' => 'Another title',
            'name' => 'Another Name'
    ),
    array(
            'name' => 'Another Name',
            'date' => 'Another date'
    ),
    array(
            'date' => 'Another date',
            'name' => 'Another Name'
    )
);

//我想要的结果

$data = array(
    array(
            'title' => 'My title',
            'name' => '',
            'date' => 'My date'
    ),
    array(
            'title' => 'Another title',
            'name' => 'Another Name',
            'date' => ''
    ),
    array(
            'title' => '',
            'name' => 'Another Name',
            'date' => 'Another date'
    ),
    array(
            'title' => '',
            'name' => 'Another Name',
            'date' => 'Another date'
    )
);

1 个答案:

答案 0 :(得分:0)

您可以使用array_map();

$data=array_map(function($element){
return [
    'title'=>isset($element['title'])?$element['title']:'',
    'name'=>isset($element['name'])?$element['name']:'',
    'date'=>isset($element['date'])?$element['date']:''
    ];

},$ data); print_r($ data);

solution