简体   繁体   English

在对象 foreach 循环中将结果限制为一个,in_array 不起作用

[英]limit result to one in object foreach loop, in_array does not work

I have a list of cities, these cities may exists once or repeated several times, or may not exists at all.我有一个城市列表,这些城市可能存在一次或重复多次,也可能根本不存在。

With php I want to check if city is in the foreach, and if exists print only one input out.使用 php 我想检查城市是否在 foreach 中,如果存在,则只打印一个输入。

Below works perfect, print city only if exist, but repeats the existing:下面完美运行,仅在存在时打印城市,但重复现有:

  **Updated (added afterwards):**
$paradasarray= array(); 
$xml = new SimpleXMLElement($viajes); 
foreach ($xml->parada as $excursion) { 
  $paradasObject = new stdClass(); 
  $paradasObject->localidad = $excursion->localidad; 
  $paradasObject->localidad = str_replace('/<![CDATA[(.*)]]>/', '', 
  $paradasObject->localidad); $paradasarray[] = $paradasObject; 
} 
$paradasarray = json_encode($paradasarray); $paradasarray = 
json_decode($paradasarray); 

     **end updated**


foreach ($paradasarray as $parada) {
    if (strpos($parada->localidad, 'Benalmádena') !== false) {
        echo '<option value="Benalmádena Costa">Benalmádena Costa</option>';
    }
    if (strpos($parada->localidad, 'Estepona') !== false) {
        echo '<option value="Estepona">Estepona</option>';
    }
}

I have tried with break, however or I only get one of the two cities when I should get both, or none of them.然而,我尝试过休息,或者我只得到两个城市中的一个,或者两个城市都没有。

You need to remove duplicate value from your array so get localidad column of array using array_column() and remove duplicate values from it using array_unique()你需要从数组中删除重复的值,从而获得localidad使用数组的列array_column()并使用从中删除重复值array_unique()

$newParadasarray = array_unique(array_column($paradasarray, "localidad"));

So your code should changed to所以你的代码应该改为

$newParadasarray = array_unique(array_column($paradasarray, "localidad"));
foreach ($newParadasarray as $parada) {
    if (strpos($parada, 'Benalmádena') !== false)
        echo '<option value="Benalmádena Costa">Benalmádena Costa</option>';

    if (strpos($parada, 'Estepona') !== false)
        echo '<option value="Estepona">Estepona</option>';
}

Check result in demo演示中检查结果


Update:更新:

I see your full code so you can create an array contain only localidad values.我看到了您的完整代码,因此您可以创建一个仅包含localidad值的数组。 and easily remove duplicate values from it using array_unique .并使用array_unique轻松地从中删除重复值。 Only add bottom code to your first loop (xml loop).仅将底部代码添加到您的第一个循环(xml 循环)。

@$newParadasarray[] = $excursion->localidad;

And remove duplicate value after loop like this并在像这样循环后删除重复值

$newParadasarray = array_unique($newParadasarray);

And loop through array to printing options并循环遍历数组到打印选项

foreach ($newParadasarray as $parada) {
    if (strpos($parada, 'Benalmádena') !== false)
        echo '<option value="Benalmádena Costa">Benalmádena Costa</option>';

    if (strpos($parada, 'Estepona') !== false)
        echo '<option value="Estepona">Estepona</option>';
}

Simply,简单地,

$cities = [];

foreach ($paradasarray as $parada) {
    // If the current city is not in our array i.e. if it hasn't been printed
    if (!in_array($parada->localidad, $cities)) {
         // print then push
         array_push($parada->localidad, $cities);
    }
}

This way you are keeping track of all the cities you have already printed.通过这种方式,您可以跟踪已打印的所有城市。

However , I would actually amend this at a query level (if a query is involved) and filter them from there.但是,我实际上会在查询级别(如果涉及查询)修改它并从那里过滤它们。

Reading Material阅读材料

array_push

You can write a break condition when 2 different matches are stored.您可以在存储 2 个不同的匹配项时编写break条件。 The beauty in declaring the $result array keys, is that if you encounter a duplicate qualifying value, it will overwrite the "group" element instead of generating a new element.声明$result数组键的好处在于,如果您遇到重复的限定值,它将覆盖“组”元素而不是生成新元素。

Code: ( Demo )代码:(演示

$paradasarray = [
    (object)['localidad' => 'Estepona whatever'],
    (object)['localidad' => 'something Benalmádena'],
    (object)['localidad' => 'Benalmádena foo'],
    (object)['localidad' => 'Estepona bar']
];

$result = [];
foreach ($paradasarray as $i => $parada) {
    if (strpos($parada->localidad, 'Benalmádena') !== false) {
        $result['Benalmádena'] = "Benalmádena Costa";
    } elseif (strpos($parada->localidad, 'Estepona') !== false) {
        $result['Estepona'] = 'Estepona';
    }
    if (count($result) == 2) {
        break;
    }
}

// you don't need to declare a value attribute if it matches the text
echo "<select>";
    echo "<option>" , implode("</option><option>", $result) , "</option>";
echo "</select>";

No matter how many elements are matched, you will either get:无论匹配多少元素,您都将获得:

0: an empty <option></option> tag in the select. 0:选择中的空<option></option>标签。
1: a single, filled option in the select 1:选择中的单个填充选项
2: both filled options in the select 2:选择中的两个填充选项

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM