回显一个数组值,给出另一个数组的密钥

时间:2018-06-06 15:09:02

标签: php arrays matching

我知道这很简单,但我无法理解它......

我有2个数组。两者都是从数据库查找填充的。

阵列1

Array ( 
[sailID] => 7 
[sailTag] => 100004 
[assigneduser] => Jason Ellmers 
[assigneddate] => 2018-05-30 17:48:57 
[cutuser] => Jason Ellmers 
[cutdate] => 2018-05-30 20:31:23 
[stickuser] => Jason Ellmers 
[stickdate] => 2018-05-30 20:38:24 
[corneruser] => Jason Ellmers 
[cornerdate] => 2018-05-30 20:38:54 
[finishuser] => Jason Ellmers 
[finishdate] => 2018-05-30 20:39:53 
[checkuser] => 
[checkdate] => 0000-00-00 00:00:00 
[DesignRef] => 420abcdefg 
[OrderingLoft] => 1 
[ClassRef] => 1 
[ClothType] => Bainbridge 
[ClothColour] => White 
[ClothWeight] => 12oz 
[SailNo] => GB342398 )

数组2

Array ( 
[0] => Array ( 
      [id] => 1 
      [name] => 420 ) 
[1] => Array ( 
      [id] => 2 
      [name] => J24 ) )

我正在做的是能够回显到屏幕$ array1 ['其中ClassRef是在Array2中查找ID'并显示来自Array2的名称]

因此,对于上面的例子,Echo将是'420'

我想我可以使用foreach或while循环来实现它,但这看起来有点麻烦???

1 个答案:

答案 0 :(得分:0)

我必须将一些测试数据放在一起,但是从评论中,我的想法是使用array_column()以id作为索引重新索引第二个数组,所以代码(就像你一样)工作了)是......

$array1 =[
    "sailID" => 7,
    "sailTag" => "100004",
    "ClassRef" => 1 ];

$array2 = [["id" => 1, "name" => "420"],
    ["id" => 2, "name" => "J24"]];

$array2 = array_column($array2, "name", "id");

echo $array2[$array1["ClassRef"]];