0

I want to make venue_ to running in loop together with the venueName. But seem it only display the last venue_ result. Any idea what wrong with my code?

$venueLength = 6;

for ($i = 0; $i < $venueLength; $i++) {
  $linkageArray = array();

  $mainArray = array ("venueName" => $venueArray[$i]['venueName']);

  for ($j = 0; $j < $venueLength; $j++) {
    $secondArray = array ( "venue_".$j => (in_array($venueArray[$j]['venueID'], $linkageArray) ? 'X' : ''));
  }

  $res[] = array_merge($mainArray, $secondArray); 
}   
header("Content-type: application/json");
$result = json_encode($res);
echo $result;

Outcome

[
  {
    venueName: "Data A",
    venue_5: ""
  },
  {
    venueName: "Data A3",
    venue_5: ""
  },
  {
  ........
]

Result I want

[
  {
    venueName: "Data A",
    venue_0: "",
    venue_1: "",
    venue_2: "",
    venue_3: "",
    venue_4: "",
    venue_5: ""
  },
  {
    venueName: "Data A3",
    venue_0: "",
    venue_1: "",
    venue_2: "",
    venue_3: "",
    venue_4: "",
    venue_5: ""
  },
  ........
]
1
  • $secondArray = array... overwriting $secondArray with every loop iteration. Last one wins. Commented Mar 19, 2020 at 7:41

1 Answer 1

2

You just keep on resetting the $secondArray value in

$secondArray = array ( "venue_".$j => (in_array($venueArray[$j]['venueID'], $linkageArray) ? 'X' : ''));

instead reset the array outside the loop and add a new value for each loop...

  $secondArray = [];
  for ($j = 0; $j < $venueLength; $j++) {
      $secondArray[ "venue_".$j ] = (in_array($venueArray[$j]['venueID'], $linkageArray) ? 'X' : ''));
  }

or just add it directly into $mainArray

  for ($j = 0; $j < $venueLength; $j++) {
      $mainArray[ "venue_".$j ] = (in_array($venueArray[$j]['venueID'], $linkageArray) ? 'X' : ''));
  }

and you don't need the array_merge().

Sign up to request clarification or add additional context in comments.

2 Comments

I try to add directly into $mainArray like you said but still not working? it get last venueName instead entire venueName's Example
Do you add the data using $res[] = $mainArray; ?

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.