检查foreach循环内的值

时间:2019-06-26 11:05:00

标签: php foreach

我有一个数组

"daily"

现在我的输出就像

library(dplyr)
library(tidyr)
library(lubridate)

sales %>%
  mutate(date = as.Date(date), 
         startdate = if_else(freq == "daily", date, floor_date(date, "month")), 
         sales = if_else(freq == "daily", sales, sales/30)) %>%
   group_by(date) %>%
   complete(date = seq(startdate, date, "1 day"), sales = sales, 
            freq = "daily", distributor = distributor) %>%
   select(-startdate)

# Groups:   date [30]
#   date       sales freq  distributor
#   <date>     <dbl> <chr> <chr>      
# 1 2019-01-01  100  daily StoreA     
# 2 2019-01-02  200  daily StoreA     
# 3 2019-01-03  300  daily StoreA     
# 4 2019-01-04  400  daily StoreA     
# 5 2019-01-01  167. daily StoreB     
# 6 2019-01-02  167. daily StoreB     
# 7 2019-01-03  167. daily StoreB     
# 8 2019-01-04  167. daily StoreB     
# 9 2019-01-05  167. daily StoreB     
#10 2019-01-06  167. daily StoreB     
# … with 25 more rows

我希望输出类似

 A[0]=array {
    title="a";
    filename="1.jpg"
    }
 A[1]=array {
    title="a";
    filename="2.jpg"
    }

所以我尝试了

A
1.jpg
A
2.jpg

运气不好,请帮助我

1 个答案:

答案 0 :(得分:1)

您需要先重新排列数组,然后从数组中打印出数据:

<?php 

$finalArray = [];

foreach($items as $item){
    $finalArray[$item['title']]['filename'][] = $item['filename']; 
}

foreach($finalArray as $key=>$value){
    echo $key.PHP_EOL;
    foreach($value['filename'] as $val){
        echo $val.PHP_EOL;
    }
    echo PHP_EOL;
    echo PHP_EOL;
}

输出:-https://3v4l.org/oklHW

注意:-如果您的初始数组是stdClass对象数组,请执行以下操作:-

$finalArray = [];

foreach($items as $item){
    $finalArray[$item->title]['filename'][] = $item->filename; 
}

foreach($finalArray as $key=>$value){
    echo $key.PHP_EOL;
    foreach($value['filename'] as $val){
        echo $val.PHP_EOL;
    }
    echo PHP_EOL;
    echo PHP_EOL;
}

输出:-{https://3v4l.org/DWrn1