我有一个foreach
循环,里面有if
语句,根据字符串包含的内容创建数组。
foreach ($dataArray2 as $item) {
$items = [];
if(strpos($item, 'your date is') !== false)
{
//Converting 22052018 to 2018-05-22
$month_words = ["may"];
$month_numbers = ["05"];
$item = str_replace($month_words, $month_numbers, $item);
$item = preg_replace('/[^0-9]/', '', $item);
$insertion = "-";
$index = 2;
$index2 = 5;
$item = substr_replace($item, $insertion, $index, 0);
$item = substr_replace($item, $insertion, $index2, 0);
$time = strtotime($item);
$date = date('Y-m-d', $time);
$items['date']= $date;
} else if (strpos($item, 'hat') !== false) {
$item = str_replace('.', '', $item);
$items['hat'] = $item;
} else {
$items['tshirt'] = $item;
}
$dataArr[] = array_filter($items);
}
echo '<pre>';
print_r($dataArr);
echo '</pre>';
数组如下所示:
[0] => Array
(
[date] => 2018-05-22
)
[1] => Array
(
[hat] => blue
)
[2] => Array
(
[tshirt] => white
)
[3] => Array
(
[hat] => black
)
[4] => Array
(
[tshirt] => cyan
)
[5] => Array
(
[date] => 2018-05-21
)
[6] => Array
(
[hat] => red
)
[7] => Array
(
[tshirt] => blue
)
我需要它看起来像:
[0] => Array
(
[0] => Array (
[date] => 2018-05-22,
[hat] => blue,
[tshirt] => white,
[hat] => black,
[tshirt] => cyan
)
[1] => Array
(
[date] => 2018-05-21
[hat] => red,
[tshirt] => blue,
)
)
EDIT:输入数组的var_export
格式:
array (
0 => 'your date is 22 may 2018, Tuesday.',
1 => 'hat: blue.',
2 => 'tshirt: white',
3 => 'hat: black.',
4 => 'tshirt: cyan',
5 => 'your date is 21 may 2018, Tuesday.',
6 => 'hat: red.',
7 => 'tshirt: blue',
编辑#2:如何将content
内的数组分解为x2块,如下所示:
Array
(
[0] => Array
(
[date] => 2018-05-22
[content] => Array
(
[0] => Array
(
[0] => blue
[1] => white
)
[1] => Array
(
[0] => black
[1] => cyan
)
[2] => Array
(
[0] => red
[1] => blue
)
)
)
[1] => Array
(
[date] => 2018-05-21
[content] => Array
(
[0] => Array
(
[0] => blue
[1] => white
)
答案 0 :(得分:1)
此方法创建一个可能的数组 而不是正则表达式来解析日期我使用较轻的日期() 由于T恤和帽子“相同”,我使用相同的方法来解析它们。
$arr = array (
0 => 'your date is 22 may 2018, Tuesday.',
1 => 'hat: blue.',
2 => 'tshirt: white',
3 => 'hat: black.',
4 => 'tshirt: cyan',
5 => 'your date is 21 may 2018, Monday.',
6 => 'hat: red.',
7 => 'tshirt: blue',
);
$i =-1;
foreach($arr as $item){
if(strpos($item, 'your date is') !== false){
$i++;
$res[$i]['date'] = date("Y-m-d", strtotime(str_replace("your date is ", "", $item)));
}else{
list($key, $val) = explode(": ", $item);
$res[$i][$key][] = rtrim($val, ".");
}
}
var_dump($res);
输出:
array(2) {
[0]=>
array(3) {
["date"]=>
string(10) "2018-05-22"
["hat"]=>
array(2) {
[0]=>
string(4) "blue"
[1]=>
string(5) "black"
}
["tshirt"]=>
array(2) {
[0]=>
string(5) "white"
[1]=>
string(4) "cyan"
}
}
[1]=>
array(3) {
["date"]=>
string(10) "2018-05-21"
["hat"]=>
array(1) {
[0]=>
string(3) "red"
}
["tshirt"]=>
array(1) {
[0]=>
string(4) "blue"
}
}
}
编辑我也纠正了你的日期。 5月21日和22日都不能是星期二。