Vinai Raj Vinai Raj - 6 months ago 9
JSON Question

Php array and json

help me to convert the following array in to json.
I tried to convert the array.

Array
(
[0] => Array
(
[c_code] => 200001
[itemname] => 303 10CAP
[c_pack_code] => PK0075
[c_web_img_link] =>
)

[1] => Array
(
[c_code] => 200005
[itemname] => 3P 4TAB
[c_pack_code] =>
[c_web_img_link] =>
)
)


current result for the following code is

public function searchOrder($idx, $data) {

if (!empty($data)) {


$result = OrderbukModel::func_get_searchlist($idx,$data);
if (!empty($result)) {
$resultArray[] = $result;
print_r(json_encode($result));
} else {
$resultArray[$idx] = ["Mysql returns empty result !"];
print_r(json_encode($resultArray));
exit;
}
}
}


now i got the result is like

[{"c_code":"200001","itemname":"303 10CAP","c_pack_code":"PK0075","c_web_img_link":""},{"c_code":"200005","itemname":"3P 4TAB","c_pack_code":"","c_web_img_link":""}]


But I need the result as follows

[{"c_code":"2000001","c_code":"200005"},
{"itemname":"303 10CAP","itemname":"3P 4TAB"},
{"c_pack_code":"PK0075","c_pack_code":""},
{"c_web_img_link":"","c_web_img_link":""}]

Answer

Example of how you can you make the json from array. Collect the data in two different array and after loop marge them and store the result in another array after that encode them.

Note: Your desired JSON is not a valid format, you can't use same index for two data.

Online Example: https://3v4l.org/kdPDI

$arr = array(
    array(
        'c_code' => '200001',
        'itemname' => '303 10CAP',
        'c_pack_code' => 'PK0075',
        'c_web_img_link' => ''
    ),
    array(
        'c_code' => '200005',
        'itemname' => '3P 4TAB',
        'c_pack_code' => '',
        'c_web_img_link' => ''
    )
);

$res1 = array();
$res2 = array();
foreach($arr as $val){
    $res1['c_code'][] = $val['c_code'];
    $res1['itemname'][] = $val['itemname'];

    $res2['c_pack_code'][] = $val['c_pack_code'];
    $res2['c_web_img_link'][] = $val['c_web_img_link'];
}

$out = array(array_merge($res1, $res2));

echo json_encode($out);