0

here is my code

array:5 [▼
   "id" => array:2 [▼
      0 => "1"
      1 => "2"
   ]
  "columnName" => array:2 [▼
     0 => "supplier"
     1 => "product"
  ]
  "status" => array:2 [▼
    0 => "1"
    1 => "0"
  ]

]

i want data like this

"1" : {
         "columnName": "supplier",
         "status": "1"
      },
"2": {
        "columnName": "product",
        "status": "0"
    }

bascially i want to get data like below format but i dont know how to do it in laravel controller using loop or without loop

DarkBee
  • 16,592
  • 6
  • 46
  • 58
  • This post may have your answer https://stackoverflow.com/questions/1869091/how-to-convert-an-array-to-object-in-php – Oskar Mikael Oct 11 '22 at 14:13

1 Answers1

1

Try the following code:

$array = [
    "id" => [
        0 => "1",
        1 => "2",
    ],
    "columnName" => [
        0 => "supplier",
        1 => "product",
    ],
    "status" => [
        0 => "1",
        1 => "0",
    ]
];

$id_list = $array['id'];
$columnName_list = $array['columnName'];
$status_list = $array['status'];

$mapped = [];
foreach ($id_list as $key => $id) {
    $mapped[$id] = [
        'columnName' => $columnName_list[$key],
        'status' => $status_list[$key],
    ];
}

try {
    $json = json_encode($mapped, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    echo "ERROR: " . $e->getMessage();
}
Roberto Braga
  • 569
  • 3
  • 8