在数组中查找字符串

时间:2017-08-13 08:30:12

标签: php arrays

好的,所以我查询数据库并从IP地址列表中生成数组:

$q = 'SELECT ip FROM proxy';
$r = mysqli_fetch_all($con->query($q), MYSQLI_ASSOC);

返回的数组如下所示:

Array
(
    [0] => Array
        (
            [ip] => 1.202.244.222
        )

    [1] => Array
        (
            [ip] => 1.226.238.136
        )

    [2] => Array
        (
            [ip] => 1.228.231.247
        )

    [3] => Array
        (
            [ip] => 1.238.106.137
        )

    [4] => Array
        (
            [ip] => 1.238.155.191
        )

但如果我想找到上述列表中的第一个或任何IP,由于某种原因它找不到任何东西:

$ip = "1.202.244.222";
if(in_array($ip,$r)) {       
echo "gotcha";       
}

我在这里做错了什么?

5 个答案:

答案 0 :(得分:2)

对数组中的数组感到困惑,我最初没有注意到。 感谢Zeth的指点,我通过添加:

将数组折叠成一个来实现它
if(in_array($ip,$r0)) {       
echo "gotcha";       
}

然后:

@Component({
selector: "recursive-selectable-structure",
template: `
    <clr-tree-node [(clrSelected)]="item.selected">
        {{item.name}}
        <recursive-selectable-structure *ngIf="item && item.children && !item.children[0]" [item]="item.children">

        </recursive-selectable-structure>
        <ng-template 
          [clrIfExpanded]="item.expanded" 
          *ngFor="let child of item.children">
            <recursive-selectable-structure
                [item]="child">
            </recursive-selectable-structure>
        </ng-template>
    </clr-tree-node>
`

答案 1 :(得分:1)

这是一个数组阵列......收起东西,然后就可以了。这里有几个选项:How to "flatten" a multi-dimensional array to simple one in PHP?

答案 2 :(得分:1)

这种情况最灵活的方法是使用用户定义的比较函数:

<?php
$needle = '1.202.244.222';
$haystack = [
    [
        'ip' => '1.202.244.222'
    ],
    [
        'ip' => '1.226.238.136'
    ],
    [
        'ip' => '1.228.231.247'
    ],
    [
        'ip' => '1.238.106.137'
    ],
    [
        'ip' => '1.238.155.191'
    ]
];

$result = array_filter($haystack, function($entry) use ($needle) {
    return isset($entry['ip']) && $needle === $entry['ip'];
});
print_r($result);

上述代码的输出显然是:

Array
(
    [0] => Array
        (
            [ip] => 1.202.244.222
        )

)

答案 3 :(得分:0)

您的阵列条件错误。

   $ip_find = '1.202.244.222';
$ip_values = [
    [
        'ip' => '1.202.244.222'
    ],
    [
        'ip' => '1.226.238.136'
    ],
    [
        'ip' => '1.228.231.247'
    ],
    [
        'ip' => '1.238.106.137'
    ],
    [
        'ip' => '1.238.155.191'
    ]
];

foreach ($ip_values as $key => $value) {
foreach ($value as $key => $ip) {
if ($ip==$ip_find) {
    echo $ip."  Gocha";
    break;
}
}
}

答案 4 :(得分:0)

你可以使用foreach:

$r = [
    [
        'ip' => '1.202.244.222'
    ],
    [
        'ip' => '1.226.238.136'
    ],
    [
        'ip' => '1.228.231.247'
    ],
    [
        'ip' => '1.238.106.137'
    ],
    [
        'ip' => '1.238.155.191'
    ]
];

$ip = "1.202.244.222";

foreach($r as $elem)
{
    if($elem['ip'] == $ip)
    {    
        echo "gotcha";
        break;
    }
}