I have this array:
array(3) {
["MANTRI KUPEDES"]=>
int(11)
["JUNIOR STAFF 1"]=>
int(10)
["PETUGAS ADM.KREDIT JUNIOR"]=>
int(10)
}
I want to change it into this:
array(3) {
[0]=>
object(stdClass)#26 (2) {
["jabatan"]=>
string(33) "MANTRI KUPEDES"
["total"]=>
int(11)
}
[1]=>
object(stdClass)#27 (2) {
["jabatan"]=>
string(33) "JUNIOR STAFF 1"
["total"]=>
int(10)
}
[2]=>
object(stdClass)#28 (2) {
["jabatan"]=>
string(30) "PETUGAS ADM.KREDIT JUNIOR"
["total"]=>
int(10)
}
}
I tried:
$jabatans['jabatan'] = array_keys($counts);
$jabatans['jumlah'] = array_values($counts);
But still didn't get what I wanted. Any ideas? I wanted to render this to CanvasJs using CodeIgniter 3.0.
CodePudding user response:
Build an array with the keys and values and cast it to an object:
foreach($array as $key => $val) {
$result[] = (object)['jabatan' => $key, 'total' => $val];
}
CodePudding user response:
I think you could do foreach loop to assign the old array to the new array of object
$array = array(
"MANTRI KUPEDES"=>11,
"JUNIOR STAFF 1"=> 10,
"PETUGAS ADM.KREDIT JUNIOR"=>10,
);
$newArray = array();
foreach ($array as $key => $val) {
$obj = new stdClass();
$obj->jabatan = $key;
$obj->total = $val;
array_push($newArray, $obj);
}
Source : https://www.php.net/manual/en/control-structures.foreach.php