Home > Blockchain >  convert array to group keys and group values in PHP
convert array to group keys and group values in PHP

Time:08-31

Hello I have an array and want to group keys and values as shown below:

[
  "agre" => "0"
  "extr" => "0"
  "inte" => "100"
]

I want to convert it to

{"labels":["agre","extr","inte"],"points":[0,0,100]}

CodePudding user response:

Just create a new array of the keys and the values.

$data = [
    "agre" => "0",
    "extr" => "0",
    "inte" => "100",
];

echo json_encode([
    'labels' => array_keys($data),
    'points' => array_map('intval', array_values($data))
]);

prints

{"labels":["agre","extr","inte"],"points":[0,0,100]}

CodePudding user response:

Try this code.

<?php
$data = array(
  "agre" => "0",
  "extr" => "0",
  "inte" => "100"
);
$newData = array('labels' => array(), 'points' => array());
foreach($data as $key => $value) {
    $newData['labels'][] = $key;
    $newData['points'][] = $value;
}
print_r($newData);
?>

Isn't this what you wanted?

  •  Tags:  
  • php
  • Related