0

I have array values like this:

   Array ( [cont_no] => Array ( [0] => 43-15 [1] => 44-18 )

Now I need to split each array values, 43-15 should be split using "-" this key and then convert into JSON type:

{"employees":[
    {"cont_no":"43", "repo_id":"15"}, 
    {"cont_no":"44", "repo_id":"18"}, 
]}
1
  • See my updated code paste it as it is Commented Feb 19, 2015 at 13:16

4 Answers 4

1

I think this would work

$jsonme =["employees"=>[]];
foreach( $ar as $a){
    $vals = explode("-", $a[0]);
    $jsonme["employees"]=[
         "yourkey1" => $vals[0],
        "yourkey2" => $vals[1]
];
$json = json_encode($jsonme);

Replace your key for what ever your want it to be in your nested json. (Also, havent tested it but i think its correct)

Sign up to request clarification or add additional context in comments.

Comments

0

Use this code

 $arr = array (cont_no => array ( 0 => '43-15', 1 => '44-18' ));

$finalArr['employees'] = array();

foreach($arr['cont_no'] as $val)
{
    $out = explode('-',$val);
    $finalArr['employees'][]['cont_no'] = $out['0'];
    $finalArr['employees'][]['repo_id'] = $out['1'];
}
echo json_encode($finalArr);

2 Comments

Almost close there $i = 0; foreach($arr as $val) { $out = explode(',',$val); $finalArr['cont_repo'][$i]['cont_no'] = $out['0']; $finalArr['cont_repo'][$i]['repo_id'] = $out['1']; $i++; } ThankYou :) Bro
"use this" answers are low value on Stack Overflow because they do very little to educate/empower the OP and thousands of researchers.
0
<?php
$src = [ 'cont_no' => [
    '43-15', '44-18'
]];

$target = array_map(
    function($e) {
        return array_combine(
            ['cont_no', 'repo_id'],
            explode('-', $e)
        );
    },
    $src['cont_no']
);


echo json_encode($target);

prints

[{"cont_no":"43","repo_id":"15"},{"cont_no":"44","repo_id":"18"}]

see also:

Comments

0

try this:

json_encode($array[0]);

Comments