Home > Back-end >  how to set id wise array create
how to set id wise array create

Time:10-11

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

CodePudding user response:

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();
}

CodePudding user response:

Easiest way I find, is to use a combination of json_decode and json_encode

You can simply do this

json_decode(json_encode($array))

This will first JSON stringify your array, and then decode it into a JSON object

  • Related