繁体   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