Search code examples
phpjsonloopstrimcharacter-trimming

Remove the last charater from string which is generated in loop


Believe me, I have tried everything that is there in stack overflow!

So, I got this JSON -

$j={
    "itempicture": [
        {
            "status": "3"
        },
        {
            "ItemCode": "001",
            "ItemImage": "image1",
            "ItemCategory": "shirt",
            "ShowOnPOS": "Yes",
            "LastModifiedOn": "2018-06-02 11:53:57"
        },
        {
            "ItemCode": "002",
            "ItemImage": "image2",
            "ItemCategory": "shirt",
            "ShowOnPOS": "Yes",
            "LastModifiedOn": "2018-06-02 11:53:57"
        }
    ]
}

and i am accessing it like this -

$jo = json_decode($j);
for($i = 1; $i < count($jo->itempicture); $i++) {
    foreach($jo->itempicture[$i] as $prop=>$val) {
        echo $val.",";
    }
    echo '<br>';
}

and I'm getting this output -

001,image1,shirt,Yes,2018-06-02 11:53:57,
002,image2,shirt,Yes,2018-06-02 11:53:57,

The main prob with this output is the "," at the last. I am unable to remove it!

Tried everything - This - Remove the last character from string

with substr, rtrim, implode... EVERYTHING!

It's not working!


Solution

  • Here is the solution

    $j='{"itempicture":[
    {
        "status":"3"
    },
    {
        "ItemCode":"001",
        "ItemImage":"image1",
        "ItemCategory":"shirt",
        "ShowOnPOS":"Yes",
        "LastModifiedOn":"2018-06-02 11:53:57"
    },
    {
        "ItemCode":"002",
        "ItemImage":"image2",
        "ItemCategory":"shirt",
        "ShowOnPOS":"Yes",
        "LastModifiedOn":"2018-06-02 11:53:57"
    }
    ]
    }';
    $jo=json_decode($j);
    $edata = '';
    for($i=1;$i<count($jo->itempicture);$i++){
        $data = '';
        foreach($jo->itempicture[$i] as $prop=>$val){
            $data .= $val.",";
        }
        $edata .= rtrim($data, ",");
        $edata .='<br/>';
    }
    
    echo "<pre>";
    print_r($edata);
    echo "</pre>";