php将字符串插入到具有键值对的数组中

时间:2017-11-11 06:13:58

标签: php arrays

编辑:已提供答案

这是我的循环,将打印day of month = # of entries per day

$count = 0;
foreach($date as $dateKey=> $dateVal) {
   echo $dateVal."=".$count;

       foreach($Posts as $PostKey => $PostVal){

        if($dateVal == $numVal) {
           echo $dateVal."=".$numVal['count'];
       }
   }

}

将打印此

01 = 0
02 = 0
03 = 12
04 = 0
05 = 13
06 = 0
07 = 16
08 = 0

如何将其推入具有键值对的数组中并使其像这样。

$arr[01 => 0, 02 => 0, 03 => 12 ...]

修改

使用它

$date = count($date)
$arr = array();
for($i = 0; $i < $date; $i++ ){
    $arr[$i]['date'] = $date[$i]; //insert in array
    $arr[$i]['count'] = 0; //if no entry for e.g(day 1) insert 0

    foreach($numbers as $PostKey => $PostVal){
        if($arr[$i]['date'] == date('d',strtotime($PostVal['date']))) {
            $arr[$i]['count'] = $PostVal['count'];
        }
    }
}

会以这种方式打印

Array ( [0] => Array ( [count] => 1 [date] => 2017-11-07 ) [1] => Array ( [count] => 1 [date] => 2017-11-09 ) [2] => Array ( [count] => 2 [date] => 2017-11-10 ) [3] => Array ( [count] => 1 [date] => 2017-11-11 ) )

1 个答案:

答案 0 :(得分:0)

您可以通过创建数组并设置其键和值来实现,如下所示:

$count = 0;
$arr = array();
foreach($date as $dateKey=> $dateVal) {
   echo $dateVal."=".$count;

       foreach($numbers as $numKey => $numVal){

        if($dateVal == $numVal) {
           $arr[$dateVal] =$numVal['count'];
       }
   }

}