簡體   English   中英

遍歷數組並按值刪除/取消設置

[英]Loop through array and delete/unset by value

我有一個來自數據庫查詢的數組:

Array
(
[0] => Array
    (
        [distance] => 14928
        [end] => 5
        [id] => 12
    )

[1] => Array
    (
        [distance] => 15645
        [end] => 2
        [id] => 1
    )

和這樣的數組:

$locations = array(
            2,3,5
        );

我要實現的目標如下:遍歷$locations數組,執行查詢並刪除等於$dbarray[0]['end']整數,然后再次執行foreach,而沒有之前的未設置值。 因此,在這種情況下:

$locations before loop = 2,3,5

$locations after loop = 2,3 (because the "end" of the first result is 5)

再次使用“新” $locations

到目前為止,我有:

$locations = array(
            2,3,5
        );    
foreach ($locations as $key => $location) {
        $query = $em->createQuery(
          'SELECT l,l.distance,l.end,l.id
           FROM AppBundle:Point l
           WHERE l.start = :startPoint
           AND l.end IN (:endPoint)
           ORDER BY l.distance ASC'
        )
        ->setParameter('startPoint', 1)
        ->setParameter('endPoint', $locations);

 $result = $query->getResult();
    unset($locations[$result[0]['end']]);
    echo $result[0]['end']."<br />";

但是echo $result[0]['end']每行只給出“ 5”。

我認為我的問題是,查詢中的$locations始終為“ 2,3,5”,不是嗎。 什么是正確的方法?

完整解決方案:

$start = 1;
    $locations = array(
        2,3,5,4
    );
    echo "<pre>";
    $em = $this->getDoctrine()->getManager($this->getUser()->getDbuser());
    foreach ($locations as $key => &$location) {
        $query = $em->createQuery(
            'SELECT l,l.distance,l.end,l.id
               FROM AppBundle:Point l
               WHERE l.start = :startPoint
               AND l.end IN (:endPoint)
               ORDER BY l.distance ASC'
            )
            ->setParameter('startPoint', 1)
            ->setParameter('endPoint', $locations);

        $result = $query->getResult();
        // Remove from array
        $locations = array_diff($locations,array($result[0]['end']));



        echo $result[0]['end']."<br />";
    }
    // Last one in the array
    echo $result[1]['end']."<br />";

可能不是最干凈的方法,但是對我有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM