0

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???

5
  • 1
    Format your arrays so that we can read them, and preferably use var_export instead. That way we can copy paste your arrays. Commented Jun 6, 2018 at 15:11
  • Convert your array2 using array_column($array2, "name", "id"); and then it will be indexed by the id. Commented Jun 6, 2018 at 15:13
  • So I would like to Echo $array1['ClassRef'], but I would like it to output '420' (from array 2) and not just '1' Commented Jun 6, 2018 at 15:21
  • Thanks @nigelren, OK so is this as short as I could get the code?? <?php $class= array_column($classes, 'name', 'id'); echo $class[$saildata['ClassRef']];?> Commented Jun 6, 2018 at 15:39
  • Why not foreach ($classes as $a) {if ($a["id"] === $saildata["ClassRef"]) {echo $a["name"];}} Commented Jun 6, 2018 at 15:42

1 Answer 1

1

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"]];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.