如何在PHP中基于邻居特定键创建数组

时间:2019-03-26 05:25:28

标签: php arrays multidimensional-array

下面是我的示例数组。如何获得邻居数组。检查邻居数组,以及下一个数组是否包含一项和key = 4。将该值添加到上一个数组

$data = array(
  array('so','item 1','details 1','date 1','qty 1'),
  array('so','item 2','details 2','date 2','qty 2'),
  array(4 => 'details of 22'),
  array('so','item 3','details 3','date 2','qty 3'),
  array(4 => 'details of 33'),
);

我期望这个结果:

Array(
    [0] => Array
        (
            [0] => so
            [1] => item 1
            [2] => details 1
            [3] => date 1
            [4] => qty 1
        )
    [1] => Array
        (
            [0] => so
            [1] => item 2
            [2] => details 2
            [3] => date 2
            [4] => qty 2
            [D] => details of 22 // added
        )
    [3] => Array
        (
            [0] => so
            [1] => item 3
            [2] => details 3
            [3] => date 2
            [4] => qty 3
            [D] => details of 33// added
        )
)

3 个答案:

答案 0 :(得分:1)

只需使用foreach迭代数组并循环检查项目的值即可。如果某项的键等于4,则将其值添加到上一项。

$newData = [];
foreach($data as $key=>$item){
    if (count($item) == 1 && isset($item[4]))
        $newData[$key-1]['D'] = $item[4];
    else
        $newData[$key] = $item;
}

demo中查看结果

答案 1 :(得分:0)

使用以下代码:

def compute(v):
    gb = ('trajectory_id',)
    global general_pd
    id = v[0]
    x = v[1]
    y = v[2]
    frame_id = v[3]
    general_pd.loc[len(general_pd)] = [id, x,y, frame_id]
    grouped = general_pd.loc[general_pd['trajectory_id'] == id]
    df_region = v[4]
    region_buffered = v[5]
    df_line = v[6]
    rpp = RawParameterProcessor(grouped, df_line, frame_idx, df_region, region_buffered,  gb=gb)
    df_parameter_car = rpp.compute()
    return df_parameter_car

答案 2 :(得分:0)

您可以遍历数组以获得预期的结果,

$res = [];
array_walk($data, function ($val, $key) use (&$res) {
    if (empty($val[0]) && !empty($val[4])) { // checking if first and forth index to merge array
        $res[count($res) - 1]['D'] = array_shift($val);
    } else {
        $res[] = $val;
    }
});
print_r($res);

array_walk —将用户提供的函数应用于数组的每个成员
array_shift —将元素移出数组的开头

输出

Array
(
    [0] => Array
        (
            [0] => so
            [1] => item 1
            [2] => details 1
            [3] => date 1
            [4] => qty 1
        )

    [1] => Array
        (
            [0] => so
            [1] => item 2
            [2] => details 2
            [3] => date 2
            [4] => qty 2
            [D] => details of 22
        )

    [2] => Array
        (
            [0] => so
            [1] => item 3
            [2] => details 3
            [3] => date 2
            [4] => qty 3
            [D] => details of 33
        )

)

Demo