The PHP solved the problem of finding the key and retrieve the value?


Warning: count(): Parameter must be an array or an object that implements Countable in /home/styllloz/public_html/qa-theme/donut-theme/qa-donut-layer.php on line 274
0 like 0 dislike
12 views
$array =[]; $array[] = [ 'id' => 1, 'name' => 'test2' ]; $array[] = [ 'id' => 2, 'name' => 'test2' ]; $array[] = [ 'id' => 3, 'name' => 'test2' ];

Python:

result = (x for x in xyz if x is.id == a)

Js:
result = xyz.find(x => x.id == a)
PHP
???
by | 12 views

6 Answers

0 like 0 dislike
$a = 3; $result = array_filter($array, function ($elem) use ($a) { return array_key_exists('id', $elem) and $elem['id'] === $a; }); if (!empty($result)) { $value = reset($result); }
by
0 like 0 dislike
Scribbled on the knee. Something like that should work.

$index = array_search($id, array_column($array, 'id')); $value = $index !== false ? $array[$index] : null;
by
0 like 0 dislike
In PHP I solve it. If I know that there will be an intensive search by id, then populate an array I'm a little crazy.
$array[3] = [ 'id' => 3, 'name' => 'test2' ];

Accordingly, "search":
$array[$a]
by
0 like 0 dislike
To get the value:
$arr['id']['test'] // 1
$arr['id']['test2'] // 2

If you need to check the key
array_key_exists('test', $arr['id']); // true
array_key_exists('test123', $arr['id']); // false
by
0 like 0 dislike
Because arrays are simple and linear, it can be passed to foreach and apply for the key, as said ipokos. For nested and non-linear arrays can offer a search function on key: https://repl.it/@Melodyn/findValuesByKeys-PHP

Array of question cost like this:
foreach ($array as $item) { echo $item['id']; }
by
0 like 0 dislike
php.net/manual/ru/language.types.array.php

Example #6 accessing array elements
<?php\r$array = array(\r"foo" => "bar", 42 => 24, "multi" => array( "dimensional" => array( "array" => "foo" ) ) ); var_dump($array["foo"]); var_dump($array[42]); var_dump($array["multi"]["dimensional"]["array"]); ?>

by

Related questions

0 like 0 dislike
3 answers
0 like 0 dislike
2 answers
0 like 0 dislike
1 answer
asked May 21, 2019 by Energy2
0 like 0 dislike
2 answers
0 like 0 dislike
1 answer
110,608 questions
257,186 answers
0 comments
35,392 users