Php 循环遍历数组并按值删除/取消设置
我有一个数据库查询中的数组:Php 循环遍历数组并按值删除/取消设置,php,mysql,arrays,Php,Mysql,Arrays,我有一个数据库查询中的数组: Array ( [0] => Array ( [distance] => 14928 [end] => 5 [id] => 12 ) [1] => Array ( [distance] => 15645 [end] => 2 [id] => 1 ) 和这样的数组: $locations =
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 />";
$locations=数组(
2,3,5
);
foreach($key=>$location的位置){
$query=$em->createQuery(
'选择l、l.距离、l.终点、l.id
从AppBundle开始:点l
其中l.start=:startPoint
和l.end IN(:端点)
按l.距离ASC'订购
)
->setParameter('startPoint',1)
->setParameter('endPoint',$locations);
$result=$query->getResult();
未设置($locations[$result[0]['end']]);
echo$result[0]['end']。“
”;
但是echo$result[0]['end']
每行只给出“5”
我想我的问题是,查询中的$位置总是“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 />";
$start=1;
$locations=数组(
2,3,5,4
);
回声“;
$em=$this->getdoctor()->getManager($this->getUser()->getDbuser());
foreach($key=>&$location形式的位置){
$query=$em->createQuery(
'选择l、l.距离、l.终点、l.id
从AppBundle开始:点l
其中l.start=:startPoint
和l.end IN(:端点)
按l.距离ASC'订购
)
->setParameter('startPoint',1)
->setParameter('endPoint',$locations);
$result=$query->getResult();
//从阵列中删除
$locations=array_diff($locations,array($result[0]['end']);
echo$result[0]['end']。“
”;
}
//数组中的最后一个
echo$result[1]['end']。“
”;
可能不是最干净的方法,但对我来说很有效。你不应该在这里为0
使用一个变量$result[0]['end']
(循环)?因为像这样你只使用位置0
,这总是一样的(5
)。好吧,不,从我的理解/尝试实现$result[0]['end']
应该始终是另一个,因为前一个已经不存在了?我只想删除第一个,所以在本例中5