在array_chunk php

时间:2015-12-17 04:56:38

标签: php arrays

我有像这样的基于数组的POST:

Array
(
[condition] => Array
    (
        [0] => 1
    )

[container] => 
[cleaning] => Y
[owner] => Eagletainer
[last_cargo] => 1
[vessel] => 
[insulation] => 1
[tare] => 
[gross] => 
[capacity] => 
[unit_type] => IMO 1
[date_of_manu] => 
[name_manu] => 
[last25] => 
[cert25] => 
[last5] => 
[cert5] => 
[list2_item_0] => 1
[list2_kondisi_0] => 9
[list3_item_0] => 15
[list3_kondisi_0] => 3
[comments] => 
)

我的情况是,我想将很多这些元素数组块化到我的数据库中的insert_batch的另一个数组中。 这是将这些数组块化的PHP代码:

public function get_partition($array, $p, $c) {
    $partition = array_slice($array, $p);
    array_pop($partition);
    return $chunk = array_chunk($partition, $c);
}

现在,使用它,

$detail = $this->get_partition($this->input->post(), 17, 2);

结果是:

Array
(
[0] => Array
    (
        [0] => 1
        [1] => 9
    )

[1] => Array
    (
        [0] => 15
        [1] => 3
    )

)

我的问题是,如何将键[0]和[1]更改为另一个键,如[ID]和[CODE_DAMAGE]

我希望他们看起来像这样:

Array
(
[0] => Array
    (
        [ID] => 1
        [CODE_DAMAGE] => 9
    )

[1] => Array
    (
        [ID] => 15
        [CODE_DAMAGE] => 3
    )

 )

5 个答案:

答案 0 :(得分:1)

重新循环数组并实现所需的结果:

$detail = $this->get_partition($this->input->post(), 17, 2);
$new_array = array();
$count = 0;
foreach($detail as $row){
   $new_array[$count]['ID'] = $row[0];
   $new_array[$count++]['CODE_DAMAGE'] = $row[1];
}

答案 1 :(得分:0)

如果索引已经正确,您可以传递可选的第三个参数:http://php.net/array_chunk

答案 2 :(得分:0)

<?php
$array = array(0 => array(0 => 123, 1 => 1234), 1 => array(0 => 123, 1 => 1234));
$updatedArray = array();
foreach ($array as $k => $v) {
    $updatedArray[$k]['ID'] = $v[0];
    $updatedArray[$k]['CODE_DAMAGE'] = $v[1];
}
?>

试试这个,我希望这有帮助。

答案 3 :(得分:0)

试试这个:

foreach($detail as $key => $value){
    if($key == 0){
        $detail['ID'] = $value;
        unset($detail[$key]);
    }
    if($key == 1){
        $detail['CODE_DAMAGE'] = $value;
        unset($detail[$key]);
    }
}

答案 4 :(得分:0)

只是一个示例将您的数组添加到此代码中..它将正常工作

$main = Array(Array(1,9),Array(15,3));
$b = array('ID', 'CODE_DAMAGE');
$new_array = array();
foreach($main as $subarray)
{
    $new_array[] = array_combine($b, $subarray);        
}
echo'<pre>';print_r($new_array);