Home  >  Q&A  >  body text

Explode array based on value

I have an array built like this

array (size=2)
  0 => 
    array (size=12)
      'id_objects' => string '2876' (length=4)
      'room_val' => string '1882840,1882841,1882842' (length=23)
      'date_from' => string '2022-06-22' (length=10)
      'date_to' => string '2022-06-22' (length=10)
  1 => 
    array (size=12)
      'id_objects' => string '2876' (length=4)
      'room_val' => string '3198723,3198724,3198726' (length=23)
      'date_from' => string '2022-06-22' (length=10)
      'date_to' => string '2022-06-22' (length=10)

What I need to achieve is, explode 'room_val' but keep the rest of the data the same, it needs to look like this

array (size=2)
  0 => 
    array (size=12)
      'id_objects' => string '2876' (length=4)
      'room_val' => string '1882840' (length=23)
      'date_from' => string '2022-06-22' (length=10)
      'date_to' => string '2022-06-22' (length=10)
1 => 
    array (size=12)
      'id_objects' => string '2876' (length=4)
      'room_val' => string '1882841' (length=23)
      'date_from' => string '2022-06-22' (length=10)
      'date_to' => string '2022-06-22' (length=10)
 
..... rest of array

is it possible?

P粉252423906P粉252423906240 days ago270

reply all(1)I'll reply

  • P粉436688931

    P粉4366889312024-02-22 13:47:34

    You need to parse the array of arrays and create a new array that matches what you are looking for.

    Similar to:

    $myNewArray = [];
    foreach ($arrays as $array) {
        $room_vals = $array['room_val'];
        foreach ($room_vals as $room_val) {
            $newSubArray = $array;
            $newSubArray['room_val'] = $room_val;
            $myNewArray[] = $newSubArray;
        }
    }

    reply
    0
  • Cancelreply