假设我有这样的数组,我从数据库中得到:
(
[0] => Array
(
[hour] => 03
[percentage] => 20
)
[1] => Array
(
[hour] => 04
[percentage] => 40
)
[2] => Array
(
[hour] => 05
[percentage] => 10
)
[3] => Array
(
[hour] => 07
[percentage] => 12
)
[4] => Array
(
[hour] => 10
[percentage] => 15
)
)
但我需要做的是如果数组中不存在小时,即1,2,6,8,9,11,12;我需要用我的百分比值0来推进数组 即
(
[0] => Array
(
[hour] => 01
[percentage] => 0
)
[1] => Array
(
[hour] => 02
[percentage] => 0
)
[2] => Array
(
[hour] => 03
[percentage] => 20
)
........
[12] => Array
(
[hour] => 12
[percentage] => 0
)
有些人可以提供任何提示如何使用它。我需要检查一天中的每个小时。
答案 0 :(得分:0)
必填:提供所有12小时的参赛作品。
$source = Array(
array('hour' => 04, 'percentage' => 40),
array('hour' => 05, 'percentage' => 10),
array('hour' => 07, 'percentage' => 10),
array('hour' => 10, 'percentage' => 15),
);
$allHours = array(); // add all empty entries, in the correct order
// note: Index starts at one not zero! It is easier
for ($hour = 1; $hour <= 12; $hour++) {
$allHours[$hour] = array( 'hour' => $hour, 'percentage' => 0);
}
// replace existing ones
foreach($source as $entry) {
$hour = $entry['hour'];
$allHours[$hour] = $entry;
}
print_r($allHours);
答案 1 :(得分:0)
让$ hour&amp; $ percent是新值
If (!array_search($hour, array_column($myarray, 'hour'))) {
$myarray[] = array ('hour' => $hour, 'percentage' => $percent);
}
答案 2 :(得分:0)
我发布我的回答可能会对你有所帮助
for($i=1;$i<=12;$i++)
{
if(!in_array( $i, array_column($data,'hour'))){
array_push($data,array('hour'=>$i,'percentage' => $percentage));
//$datas[] =array('hour'=>$hour,'percentage' => $percentage);
}
}