Jason Ellmers
Jason Ellmers

Reputation: 65

echoing an array value giving a key from another array

I know this is simple, but cant get my head around it...

I have 2 arrays. Both populated from a database lookup.

Array 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 )

Array 2

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

What I am after doing is being able to echo to the screen $array1['Where the ClassRef is a lookup of the ID in Array2' and displays the Name from Array2]

So for the above example the Echo would be '420'

I think I could do it using a foreach or while loop but that seems a bit cumbersome???

Upvotes: 0

Views: 50

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57131

I've had to put some test data together, but from the comment, the idea is to re-index the second array using array_column() with the id as the index, so the code (as you've worked out) is...

$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"]];

Upvotes: 1

Related Questions