我想要一个来自 PHP 数组的特定格式数组

我想将现有数组修改为特定格式,请参阅下面的数组我拥有什么和我想要什么


我有数组:


Array

(

    [0] => Array

        (

            [block_id] => 1

            [title] => Test1

            [identifier] => test1

            [content] => some test data

            [creation_time] => 2019-09-03 09:47:35

            [update_time] => 2019-09-03 09:47:35

            [is_active] => 1

        )


    [1] => Array

        (

            [block_id] => 2

            [title] => test2

            [identifier] => twst2

            [content] => dfdsffsdfsdfsfsdf

            [creation_time] => 2019-09-03 09:48:03

            [update_time] => 2019-09-03 09:48:03

            [is_active] => 1

        )


)

我希望这个数组为:


$options = [

        ['value' => 'test1', 'label' => __('Test1')],

        ['value' => 'test2', 'label' => __('Test2')],

        ['value' => 'test3', 'label' => __('Test3')],

        ['value' => 'test4', 'label' => __('Test4')],

        ['value' => 'test5', 'label' => __('Test5')],

        ['value' => 'test6', 'label' => __('Test6')]

        ];



有只小跳蛙
浏览 114回答 3
3回答

肥皂起泡泡

如果您正在尝试“将现有数组修改为特定格式”,则下一种方法可能会有所帮助。当你在前面$value时&,$value将通过引用分配,你可以直接修改它。<?phpforeach($array as &$value) {&nbsp; &nbsp; $value = array(&nbsp; &nbsp; &nbsp; &nbsp; 'value' => $value["identifier"],&nbsp; &nbsp; &nbsp; &nbsp; 'label' => "__('".$value["title"]."')"&nbsp; &nbsp; );};unset($value);?>

牛魔王的故事

如果 $array 是你的数组,那么foreach ($array as $k => $v){&nbsp; &nbsp; $options[] = [ 'value' => $v['identifier'], 'label' => "__('" . $v['title'] . "')"];}

宝慕林4294392

试试这个解决方案。$data = Array ( Array&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'block_id' => 1,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'title' => 'Test1'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ), Array&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'block_id' => 2,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'title' => 'test2'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; foreach($data as $k => $val){&nbsp; &nbsp; &nbsp; &nbsp; $options[$k]['value'] = $val['title'];&nbsp; &nbsp; &nbsp; &nbsp; $options[$k]['label'] = '__("'.ucfirst($val['title']).'")';&nbsp; &nbsp; }&nbsp; &nbsp; echo "<pre>";&nbsp; &nbsp; print_r( $options);预期结果是&nbsp; &nbsp; Array(&nbsp; &nbsp; [0] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [value] => Test1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [label] => __("Test1")&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; [1] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [value] => test2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [label] => __("Test2")&nbsp; &nbsp; &nbsp; &nbsp; ))
打开App,查看更多内容
随时随地看视频慕课网APP