-1

I have written a query on database the result is given in this form

Apples-100
Grapes-200
Oranges-50
Bananas-30

now i need to store the data in an array like this

[['Apples',100],['Grapes',200],['Oranges',50],['Bananas',30]]

how can I acheive this i tried this

while($row = mysql_fetch_assoc($getdatagraoh)){ 
    $plotgraphs[] = array(
        $row['Compliancestatus'],
        $row['value']
    );
}
header('ContentType: application/json; charset=utf-8');
$data= json_encode($plotgraphs);

I am not able to acheive that.Please help me in this regard.

Noor
  • 1,345
  • 7
  • 27
Firoz
  • 476
  • 2
  • 6
  • 21

5 Answers5

2

First do not use mysql_* as its depcrated instead use mysqli_* or PDO.

Back to your question once you have stored values in $plotgraphs then explode like this and you will get the required result

foreach ( $array as $k => $v ) {
    $seprated = explode ( '-', $v );

    //echo '<pre>';
    //print_r ( $seprated );
    echo json_encode(( $seprated ));
}

Output

["Apples","100"]["Grapes","200"]["Oranges","50"]["Bananas","30"]
Noor
  • 1,345
  • 7
  • 27
1
while($row = mysql_fetch_assoc($getdatagraoh)){ 
  $plotgraphs[] =$row;
}

Side note: Why shouldn't I use mysql_* functions in PHP?

Community
  • 1
  • 1
Emilio Gort
  • 3,450
  • 3
  • 28
  • 44
0

Try this:

<?php
$plotgraphs = array();

while($row = mysql_fetch_assoc($getdatagraoh)){ 
    $plotgraphs[] = $row;
}
?>

Here $row array is assigned to $plotgraphs.

Dipesh Parmar
  • 26,601
  • 7
  • 57
  • 86
Anand Solanki
  • 3,370
  • 4
  • 15
  • 27
0
var $plotgraphs = [];  
  while( $row = mysql_fetch_assoc( $getdatagraoh)){
        $plotgraphs[] = $row; // Inside while loop
        //or
        $plotgraphs[ $row['id']] = $row;
    }
Prateek
  • 6,629
  • 2
  • 23
  • 37
0

Try like this : Since you have change question you can try this one :

$arrayName = array('Apples-100','Grapes-200','Oranges-50','Bananas-30');



foreach($arrayName as $value)
{
     $plotgraphs = explode("-",$value);
   echo  json_encode( $plotgraphs);
}

OUTPUT: ["Apples","100"]["Grapes","200"]["Oranges","50"]["Bananas","30"]

OR

foreach($arrayName as $value)
{
     $plotgraphs[] = explode("-",$value);

}
echo json_encode( $plotgraphs);
Mahmood Rehman
  • 4,295
  • 7
  • 37
  • 74