当我有一个数组的唯一值时,如何从关联数组中获取数组的其他元素[关闭]

当我有一个数组的唯一值时,如何从关联数组中获取数组的其他元素[关闭]

问题描述:

Array
(
    [0] => Array
        (
            [id] => 61
            [title] => werwer
        )

    [1] => Array
        (
            [id] => 63
            [title] => test
        )

    [2] => Array
        (
            [id] => 88
            [title] => test 2
        )
)

How can I get title which has id=63 in above type of array without looping.

Actually, you can't do that without looping. That doesn't mean you have to use loop (foreach/while e t.c.) - but using array functions you will internally iterate array in any case.

For example, in PHP 5.5 that is:

$array = [
['id'=>63, 'title'=>'foo'],
['id'=>65, 'title'=>'bar']
];
//use this - if there are more than 2 connected to `id` fields:
$ids    = array_flip(array_column($array, 'id'));//here is iteration, gathering id column
$result = $array[$ids[63]]['title'];
//or else, if `title` is always the only field:
$result = array_column($array, 'title', 'id')[63];
//var_dump($result);

-and so on. array_search() with array_walk() (or similar ways) will hide iteration from you, but it will be done in any case.

No way to get it without a loop if you don't already know the index of the id 63 in the array.

foreach($array as $element) {
    if($element['id'] == 63) {
        echo $element['title'];
    }
}

You could change the structure of the array:

$array = array(61 => 'werwer', 63 => 'test', 88 => 'test 2');

That would result in:

Array
(
    [61] => 'werwer'
    [63] => 'test'
    [88] => 'test 2'
)

Then you could access/get it with $array[63]

Well You can try some crazy stuff like this

array_search(61,
    array_combine(
            array_map(function ($a) {
                return $a['title'];
            }, $arr),
            array_map(function ($a) {
                return $a['id'];
            }, $arr)));

but it's highly uneffective (there are 4 loops 'hidden' in 2 array_map, array_combine, and array_search). I advise to use looping - just like @JustAPirate wrote.

$arr = array(array('id' => 61, 'title' => 'werwer'),
        array('id' => 62, 'title' => 'asdasd'),
        array('id' => 63, 'title' => 'qweqwe'),);

function f($arr, $id) {
    foreach ($arr as $a) {
        if ($a['id'] == $id)
            return $a['title'];
    }
}

var_dump(f($arr, 61));