Skip to content
Advertisement

how to convert $request format in laravel

I search around for a bit but found nothing that did exactly what I’m after nor anything that really aided me in achieving what I’d like

I have data in this format:

array:4 [▼
  "name" => array:2 [▼
    0 => "ty"
    1 => "word"
  ]
  "phone" => array:2 [▼
    0 => "2222222"
    1 => "3333333"
  ]
  "email" => array:2 [▼
    0 => "abc@gmail.com"
    1 => "xyz@gmail.com"
  ]
  "cnic" => array:2 [▼
    0 => "567"
    1 => "234"
  ]
]

I’d like to convert it all to this format:

   [
  {
    "name" => "ty"
    "phone" => "2222222"
    "email" => "abc@gmail.com"
    "cnic" => "567"
  },
  {
    "name" => "word"
    "phone" => "3333333"
    "email" => "xyz@gmail.com"
    "cnic" => "234"
  }
]

i tried:

foreach ($array as $key => $value) {
    $x = count($array[0]["name"]);
    for ($i=0; $i < $x; $i++) { 
        $newArray[] = [$value["name"][$i], $value["phone"][$i], $value["email"][$i] ,$value["cnic"][$i]];
    }
}

but get no success

Advertisement

Answer

You got it the other way around. You need to loop on the rows first (0 and 1), then in each column (name, phone, email, cnic), loop each value:

$newArray = [];
$count = count($array['name']);
for ($i = 0; $i < $count; $i++) {
    $temp = [];
    foreach (array_keys($array) as $key) {
        $temp[$key] = $array[$key][$i] ;
    }
    $newArray[] = $temp;
}

Or using array_combine + array_keys + array_column would work as well:

$newArray = [];
for ($i = 0, $count = count($array['name']); $i < $count; $i++) {
    $newArray[] = array_combine(array_keys($array), array_column($array, $i));
}

Sample Output

Sidenote: If this came from a form, I think this is the classic case of <input name="name[]" in your html form.

If you follow this kind of structure:

<form>
    <div class="form-group">
        <input name="input[0][name]" />
        <input name="input[0][email]" />
        <input name="input[0][phone]" />
        <input name="input[0][cnic]" />
    </div>

    <div class="form-group">
        <input name="input[1][name]" />
        <input name="input[1][email]" />
        <input name="input[1][phone]" />
        <input name="input[1][cnic]" />
    </div>
</form>

You would not need to do such array transposition in PHP. Once you submit the form, you already got yourself your expected array structure above. But that’s just an assumption on my part.

If it doesn’t come from a form, feel free to disregard this sidenote.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement