假设, 我有一个数组
$my_array = array(
array(
array('cnt' => 1, 'date' => '2016-06-18', 'name' => 'Phone Calls'),
array('cnt' => 1,'date' => '2016-06-18','name' => 'Others Works')
),
array(
array('cnt' => 2 , 'date' => '2016-06-17', 'name' => 'Phone Calls'),
array('cnt' => 1, 'date' => '2016-06-17', 'name' => 'Others Works'),
array('cnt' => 1, 'date' => '2016-06-17', 'name' => 'Deal with Customer')
),
array(
array('cnt' => 4 , 'date' => '2016-06-15', 'name' => 'Phone Calls'),
array('cnt' => 5, 'date' => '2016-06-15', 'name' => 'Others Works'),
array('cnt' => 6, 'date' => '2016-06-15', 'name' => 'Deal with Customer')
)
.....
);
我需要转换成
$desired_result = array(
array('date' => '2016-06-18',
'Phone Calls' => 1,//value is cnt of my_array
'Others Works' => 1,//value is cnt of my_array
),
array('date' => '2016-06-17',
'Phone Calls' => 2,//value is cnt of my_array
'Others Works' => 1,//value is cnt of my_array
'Deal with Customer' => 1,
),
array('date' => '2016-06-15',
'Phone Calls' => 4,//value is cnt of my_array
'Others Works' => 5,//value is cnt of my_array
'Deal with Customer' => 6,
)
.......
);
我需要按数组对数组进行分组,其中数组名称与key相同,cnt为value。任何人都可以建议我如何格式化此数组。
我想试试http://bl.ocks.org/katirg/5f168b5c884b1f9c36a5。
我是d3js的新手,所以我想我会更好地格式化我的数组。
答案 0 :(得分:0)
您需要循环外部数组,然后循环每个数组。获取索引名称并在值为该数组cnt。
的新数组中创建索引$my_array = array(
array(
array('cnt' => 1, 'date' => '2016-06-18', 'name' => 'Phone Calls'),
array('cnt' => 1,'date' => '2016-06-18','name' => 'Others Works')
),
array(
array('cnt' => 2 , 'date' => '2016-06-17', 'name' => 'Phone Calls'),
array('cnt' => 1, 'date' => '2016-06-17', 'name' => 'Others Works'),
array('cnt' => 1, 'date' => '2016-06-17', 'name' => 'Deal with Customer')
),
array(
array('cnt' => 4 , 'date' => '2016-06-15', 'name' => 'Phone Calls'),
array('cnt' => 5, 'date' => '2016-06-15', 'name' => 'Others Works'),
array('cnt' => 6, 'date' => '2016-06-15', 'name' => 'Deal with Customer')
)
);
$betterFormat = array();
foreach($my_array as $arrays){
$newArray = array();
//Assume the date is the same in both arrays
$newArray['date'] = $arrays[0]['date'];
foreach($arrays as $arr){
$newArray[$arr['name']] = $arr['cnt'];
}
$betterFormat[] = $newArray;
}
echo "<pre>";
var_dump($betterFormat);
输出
array(3) {
[0]=> array(3) {
["date"]=> string(10) "2016-06-18"
["Phone Calls"]=> int(1)
["Others Works"]=> int(1)
}
[1]=> array(4) {
["date"]=> string(10) "2016-06-17"
["Phone Calls"]=> int(2)
["Others Works"]=>int(1)
["Deal with Customer"]=> int(1)
}
[2]=> array(4) {
["date"]=> string(10) "2016-06-15"
["Phone Calls"]=> int(4)
["Others Works"]=> int(5)
["Deal with Customer"]=> int(6)
}
}