Home > Back-end >  How to create a new variable/array using exisiting array?
How to create a new variable/array using exisiting array?

Time:01-25

I need to create two variables(not sure whether it can also called as an array) by using existing arrays. Let's day I need two variables such as,

$Date =['2022-01-10', '2022-01-11', '2022-01-12', '2022-01-13'];
$Value =[91, 12,15,16];

I am planning to get these two values by using a sql query.

$query = "select Date,Value from shop order by Date asc;";

$result=mysqli_query($conn,$query);

while( $row = mysqli_fetch_assoc( $result)){
    $new_array[] = $row;
}

$date_array = array();
$value_array=array();
foreach($new_array as $array)
{       
   $date_array[]=$array['Date'];
   $value_array[]=$array['Value'];
   

}
$date_array_vals=array_values($date_array);
$value_array_vals=array_values($value_array);

I have now $date_array_vals and $value_array_vals as below.

Array ( [0] => 2022-01-02 [1] => 2022-01-03 [2] => 2022-01-04 [3] => 2022-01-05 )
Array ( [0] => 20.8 [1] => 201.5 [2] => 25.6 [3] => 205.5 ) 

How I could retrieve $Date and $Value as above mentioned?

update: Eventually I need to add these two arrays to following code.

$chartConfig = "{
    type: 'bar',
    data: {
      labels: [//$date should added],
      datasets: [{
        data: [//$value should added],
        backgroundColor: ['#b87333', 'silver', 'gold', '#e5e4e2'],
      }]
    },
    options: {
      title: {
        display: true,
        text: 'Density of Precious Metals, in g/cm^3',
      },
      legend: {
        display: false    
      }
    }
  }";
 

CodePudding user response:

Do this $date = implode(',',$Date); And in html page Do this var date = "{$date}"

var datearr = date.split(',');

for value do the same above with

var valuearr = value.split(',').map(Number);

CodePudding user response:

Create $chartconfig using json_encode() after creating the array.

$query = "select Date,Value from shop order by Date asc;";

$result=mysqli_query($conn,$query);

while( $row = mysqli_fetch_assoc( $result)){
    $Date = $row['Date'];
    $Value = $row['Value'];
}

$chart = [
    "type" => 'bar',
    "data" => [
        "labels" => $Date,
        "datasets" => [[
            "data" => $Value,
            "backgroundColor" => ['#b87333', 'silver', 'gold', '#e5e4e2'],
        ]]
    ],
    "options" => [
        "title" => [
            "display" => true,
            "text" => 'Density of Precious Metals, in g/cm^3',
        ],
        "legend" => [
            "display" => false    
        ]
    ]
];

$chartConfig = json_encode($chart);
  •  Tags:  
  • Related