我有以下数组:
Array
(
[0] => Array
(
[id] => pencil
[label] => blue pencil 123
)
[1] => Array
(
[id] => eraser
[label] => green eraser 123
)
)
我知道id(橡皮擦)但我不知道标签(绿色橡皮擦123),如何通过已知的唯一ID(橡皮擦)获得标签(绿色橡皮擦123)?
我可以在循环中为每个元素执行此操作吗?
答案 0 :(得分:0)
试试这个:
$arr = [
[
'id' => 'pencil',
'label' => 'blue pencil 123',
],
[
'id' => 'eraser',
'label' => 'green eraser 123',
],
];
function getLabelFromId ($arr, $id) {
foreach ($arr as $row) {
if ($row['id'] == $id) {
return $row['label'];
}
}
return null;
}
var_dump(getLabelFromId($arr, 'pencil'));
var_dump(getLabelFromId($arr, 'eraser'));
输出:
string(15) "blue pencil 123"
string(16) "green eraser 123"