如何根据数组值分配id

时间:2016-06-27 05:34:17

标签: php

我正在学习php请帮助。

我在数组中存储值,然后我试图获取另一个数组的id检查数组中的值,如下所示:

$arr_folders = ['one', 'two', 'whatever'];

$id_one = '';
$id_two = '';
$id_whatever = '';
foreach ($tree as $key => $value) {
  if($value['name'] == 'one'){//how to check dynamically?
    $id_one = $value['id'];
  }
  if($value['name'] == 'two'){//how to check dynamically?
    $id_two = $value['id'];
  }
  if($value['name'] == 'whatever'){//how to check dynamically?
    $id_whatever = $value['id'];
  }
}
echo $id_whatever;

如何动态检查数组值。我的意思是我想检查数组中是否存在值,然后分配它们的id。

4 个答案:

答案 0 :(得分:0)

尝试使用数组搜索

例如:

<?php 
$arr_folders = ['one', 'two', 'whatever'];

foreach ($tree as $key => $value) {
  if (($key = array_search($arr_folders, $value)) !== false) {
    return $arr_folders[$key];
  }
}
echo $id_whatever;

答案 1 :(得分:0)

如果我理解了这个问题,你就会问如何在循环访问另一个数组的过程中检查一个数组的内容(在本例中为content),而不对其进行硬编码。如果是这种情况,我可能会尝试这样的事情:

[one, two, whatever]

可能还有其他更优雅或时间效率更高的解决方案,但我认为这可以捕捉您正在寻找的动态特性,同时镜像前一代码的实际过程。

答案 2 :(得分:0)

您需要使用in_array来检查该元素是否存在于另一个数组中,如果找到,您可以根据需要创建包含$value['name']的{​​{1}}动态变量。< / p>

$value['id']

工作示例:https://eval.in/596034

注意:请确保$tree = [ ['id' => 1, 'name' => 'one'], ['id' => 2, 'name' => 'two'], ['id' => 3, 'name' => 'three'] ]; $arr_folders = ['one', 'two', 'whatever']; foreach ($tree as $key => $value) { if (in_array($value['name'], $arr_folders)) { ${'id_'.$value['name']} = $value['id']; } } echo $id_one; 不包含空格或任何其他不允许声明变量名称的字符。

答案 3 :(得分:0)

这是示例代码:

<?php
$arr_folders = ['one', 'two', 'whatever'];
$tree= Array(Array('id' => 1,'name' => 'one'),
             Array('id' => 2,'name' => 'large'),
             Array('id' => 3,'name' => 'thumb'),
             Array('id' => 4,'name' => 'two'),
             Array('id' => 5,'name' => 'large'),
             Array('id' => 6,'name' => 'thumb')
        );

foreach ($tree as $key => $value) {
    if(in_array($value['name'],$arr_folders)){
        $searchedIds[] = $value['id'];
    }
}
print_r($searchedIds);
?>