数组格式的PHP

时间:2019-01-22 20:26:47

标签: php mysql codeigniter

我需要更改在CodeIgniter中返回的数组的格式,将数据库的字段保留为索引,我在PHP和CodeIgniter中进行了相同的查询,并且两者是不同的,有什么建议吗?我在CodeIgniter中使用result_array(),也在result()中使用

我需要这个:

Array
(
    [1_1] => Array
        (
            [0] => 1_1
            [1] => 16
            [2] => ch
            [3] => Chemistry
        )

    [1_2] => Array
        (
            [0] => 1_2
            [1] => 17
            [2] => ch
            [3] => Chemistry
        )

    [2_3] => Array
        (
            [0] => 2_3
            [1] => 18
            [2] => ch
            [3] => Chemistry
        )

    [2_5] => Array
        (
            [0] => 2_5
            [1] => 19
            [2] => ch
            [3] => Chemistry
        )

    [9_1] => Array
        (
            [0] => 9_1
            [1] => 20
            [2] => ch
            [3] => Chemistry
        )

)

查询结果:

Array
(
    [0] => Array
        (
            [pos] => 1_1
            [tbl_id] => 16
            [sub_id] => ch
            [sub_name] => Chemistry
        )

    [1] => Array
        (
            [pos] => 1_2
            [tbl_id] => 17
            [sub_id] => ch
            [sub_name] => Chemistry
        )

    [2] => Array
        (
            [pos] => 2_3
            [tbl_id] => 18
            [sub_id] => ch
            [sub_name] => Chemistry
        )

    [3] => Array
        (
            [pos] => 2_5
            [tbl_id] => 19
            [sub_id] => ch
            [sub_name] => Chemistry
        )

    [4] => Array
        (
            [pos] => 9_1
            [tbl_id] => 20
            [sub_id] => ch
            [sub_name] => Chemistry
        )

)

如何删除开头的数组?谢谢。

1 个答案:

答案 0 :(得分:1)

$array = [
    [
        'pos' => '1_1',
        'tbl_id' => 16,
        'sub_id' => 'ch',
        'sub_name' => 'Chemistry'
    ]
];


$result = [];
foreach ($array as $data) {
    $values = array_values($data);

    $result[$data['pos']] = $values;
}

这将为您提供想要的东西。

Array
(
    [1_1] => Array
        (
            [0] => 1_1
            [1] => 16
            [2] => ch
            [3] => Chemistry
        )

)