Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array format to JSON format [closed]

Using this array value change this to JSON format.

    $prices = array("250", "350", "400", "678", "800", "1000");
    var opt = {
    milestones: {
    1: {
         mlPos: 250, ---> (set $price value)
         mlId: false,
         mlClass: 'bi-custom',
         mlDim: '200%',
         mlLabel: 'Milestone one',
         mlLabelVis: 'hover',
         mlHoverRange: 15,
         mlLineWidth: 1
       },
    2: {
        mlPos: 350, ---> (set $price value)
        mlId: false,
        mlClass: 'bi-custom',
        mlDim: '200%',
        mlLabel: 'Milestone two',
        mlLabelVis: 'hover',
        mlHoverRange: 15,
        mlLineWidth: 1
     },
     3: {
       mlPos: 400, ---> (set $price value)
       mlId: false,
       mlClass: 'bi-custom',
       mlDim: '200%',
       mlLabel: 'Milestone one',
       mlLabelVis: 'hover',
       mlHoverRange: 15,
       mlLineWidth: 1
     },
  4: {
      mlPos: 678,---> (set $price value)
      mlId: false,
      mlClass: 'bi-custom',
      mlDim: '200%',
      mlLabel: 'Milestone two',
      mlLabelVis: 'hover',
      mlHoverRange: 15,
      mlLineWidth: 1
    },
 5: {
     mlPos: 800,---> (set $price value)
     mlId: false,
     mlClass: 'bi-custom',
     mlDim: '200%',
     mlLabel: 'Milestone two',
     mlLabelVis: 'hover',
     mlHoverRange: 15,
     mlLineWidth: 1
   }
 }
};

We have the php variable in array format $price convert in javascript variable like this json format,problem is not for converting php variable into javascript variable problem is just convert the php array into json format like above format.

anyone please help

Thank You.

like image 704
karthik Avatar asked Mar 30 '26 02:03

karthik


1 Answers

Before you use json_encode cast the arrays into objects, you can also use JSON_FORCE_OBJECT option for that:

$prices = array( "250", "350", "400", "678", "800", "1000" );

$row = [
    'mlPos'         => null,
    'mlId'          => false,
    'mlClass'       => 'bi-custom',
    'mlDim'         => '200%',
    'mlLabel'       => 'Milestone two',
    'mlLabelVis'    => 'hover',
    'mlHoverRange'  => 15,
    'mlLineWidth'   => 1
];

$rows = [];
foreach( $prices as $price ) {
    $rows[] = (object) array_replace( $row, [ 'mlPos' => $price ] );
}

$opt = [ 'milestones' => (object) $rows ];


echo json_encode( $opt,  JSON_FORCE_OBJECT );

// output {"milestones":{"0":{"mlPos":"250","mlId":false,"mlClass":"bi-custom", ...
like image 174
Danijel Avatar answered Apr 02 '26 02:04

Danijel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!