如何在数组动态php中添加数组?

时间:2016-06-29 06:35:07

标签: php arrays

我想克里特这样的事情

Array
 (
    [0] => Array
      (
        [id] => 1
        [name] => open
        [task] => Array
                 (
                 [0] => Array
                 (
                     [id] => 2
                     [project_id] => 1
                     [name] => task 2 from pro1
                     [card] => 1
                 )
                 )
      )

)

用这个

Araay - 1: -

Array
 (
    [0] => Array
      (
        [id] => 1
        [name] => open
    )

 )

数组 - 2: -

Array
(
[0] => Array
    (
        [id] => 2
        [project_id] => 1
        [name] => task 2 from pro1
        [card] => 1
    )
)

现在,让我们假设array-1是一个卡阵列,array-2是任务阵列,现在有多个卡和任务。我需要在卡所属的卡上设置任务,这就是为什么我在两个阵列中都有卡ID。如果卡阵列的id为1且任务也有[card] => 1然后它在那个阵列中定居。

帮助是先进的欣赏和感谢。

这是代码:

$get_card_qry = "select * from tts_card where project_id = '1' ";
$get_card_res = $conn -> query($get_card_qry);


$cad = $task = array();
while($row = $get_card_res -> fetch_assoc())
{
    array_push($cad, $row);
    $get_task_qry = "select * from tts_task where card = '".$row['id']."' ";
    $get_task_res = $conn -> query($get_task_qry);
    while($row1 = $get_task_res -> fetch_assoc())
    {
        array_push($task , $row1);
    }
}

1 个答案:

答案 0 :(得分:0)

使用常规foreach循环的简单解决方案:

$cards = [0 => ['id' => 1, 'name' => 'open']];
$tasks = [  // add one more item/task for complex case
    0 => ['id' => 2, 'project_id' => 1,  'name' => 'task 2 from pro1', 'card' => 1],
    1 => ['id' => 3, 'project_id' => 2,  'name' => 'task 3 from pro1', 'card' => 1]
];

foreach ($cards as &$card) {
    foreach ($tasks as $task) {
        if ($task['card'] === $card['id']) $card['task'][] = $task;
    }
}

print_r($cards);

输出:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => open
            [task] => Array
                (
                    [0] => Array
                        (
                            [id] => 2
                            [project_id] => 1
                            [name] => task 2 from pro1
                            [card] => 1
                        )

                    [1] => Array
                        (
                            [id] => 3
                            [project_id] => 2
                            [name] => task 3 from pro1
                            [card] => 1
                        )
                )
        )
)