如何在php中检查数组2维索引而没有循环? [英] How can I check index in array 2 dimensional without loop in php?

查看:48
本文介绍了如何在php中检查数组2维索引而没有循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这样尝试:

<?php 
    $list_team = array( 
                (object)array(
                    'id' => 1, 
                    'name' => 'chelsea.jpg'
                ),
                (object)array(
                    'id' => 2, 
                    'name' => 'mu.jpg'
                ),
                (object)array(
                    'id' => 3, 
                    'name' => 'arsenal.jpg'
                ),
            );

    $team = 'chelsea.jpg';

    echo '<pre>';print_r($team);echo '</pre>';
    echo '<pre>';print_r($list_team);echo '</pre>';

    foreach($list_team as $key => $value) {
        if($value->name == $team)
            $team_selected = $team;
    }
    echo '<pre>';print_r($team_selected);echo '</pre>';
    die();
?>

如果执行了代码,则结果如下:

If the code executed, the result like this :

chelsea.jpg

Array

(

[0] => stdClass Object   ( [id] => 1

[name] => chelsea.jpg

)

[1] => stdClass Object

(

[id] => 2

[name] => mu.jpg

)

[2] => stdClass Object

(

[id] => 3

[name] => arsenal.jpg

)

)

chelsea.jpg

使用循环的代码

但是,我不想使用循环

我该怎么办?

推荐答案

使用 array_search() array_column()

<?php

$list_team = array( 
                (object)array(
                    'id' => 1, 
                    'name' => 'chelsea.jpg'
                ),
                (object)array(
                    'id' => 2, 
                    'name' => 'mu.jpg'
                ),
                (object)array(
                    'id' => 3, 
                    'name' => 'arsenal.jpg'
                ),
            );

    $team = 'chelsea.jpg';

    // array column, returns all value of sub array, with key name
    // array_search will return key
    $key = array_search($team, array_column($list_team, 'name'));

    if($key!==false){

        // your object will be
        print_r($list_team[$key]);

        // access remaining..
        echo $list_team[$key]->name.' '. $list_team[$key]->id.PHP_EOL;
    }
?>

这篇关于如何在php中检查数组2维索引而没有循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆