我已经花了很长时间来解决这个问题,而且我不能为我的生活弄清楚。任何帮助将不胜感激!
我有一个字符串数组,我用它来获取信息,即事件的月份隐藏在url(字符串)中,我想循环遍历所有的URL并获得月份,并且其他数据输出并使每个数据片成为它自己的数组。
这里的交易,我可以成功完成两次,但第三次尝试创建阵列时,它会崩溃。
此代码有效:
$months = array();
$times = array();
foreach ($ticketsLinks as $ticketsLink){
//CREATE VENUE ARRAY
// Delete all the way up to "-tickets-"
$findMeA = '-tickets-';
$posA = strpos($ticketsLink, $findMeA);
$posA = $posA + 9;
$venue = substr($ticketsLink, $posA);
// Find the first number in the string - delete everything after that.
$lengthA = strlen($venue);
$parts = str_split($venue);
$first_num = -1;
$num_loc = 0;
foreach ($parts AS $a_char) {
if (is_numeric($a_char)) {
$first_num = $num_loc;
break;
}
$num_loc++;
}
$posB = -$lengthA + $num_loc - 1;
$venue = substr($venue, 0, $posB);
// Replace dashes with spaces.
$venue = str_replace("-"," ",$venue);
//Add value to venue's array
$venues[] = $venue;
// CREATE TIME ARRAY
$pos = strrpos($ticketsLink, '-');
$pos = strlen($ticketsLink) - $pos - 1;
$time = substr($ticketsLink, -$pos);
$pos = strpos($time, '/');
$time = substr($time, 0, $pos);
$times[] = $time;
}
此代码不会:
$months = array();
$times = array();
$years = array();
foreach ($ticketsLinks as $ticketsLink){
//CREATE VENUE ARRAY
// Delete all the way up to "-tickets-"
$findMeA = '-tickets-';
$posA = strpos($ticketsLink, $findMeA);
$posA = $posA + 9;
$venue = substr($ticketsLink, $posA);
// Find the first number in the string - delete everything after that.
$lengthA = strlen($venue);
$parts = str_split($venue);
$first_num = -1;
$num_loc = 0;
foreach ($parts AS $a_char) {
if (is_numeric($a_char)) {
$first_num = $num_loc;
break;
}
$num_loc++;
}
$posB = -$lengthA + $num_loc - 1;
$venue = substr($venue, 0, $posB);
// Replace dashes with spaces.
$venue = str_replace("-"," ",$venue);
//Add value to venue's array
$venues[] = $venue;
// CREATE TIME ARRAY
$pos = strrpos($ticketsLink, '-');
$pos = strlen($ticketsLink) - $pos - 1;
$time = substr($ticketsLink, -$pos);
$pos = strpos($time, '/');
$time = substr($time, 0, $pos);
$times[] = $time;
// CREATE YEAR ARRAY
$pos = strrpos($ticketsLink, '-');
$pos = strlen($ticketsLink) - $pos - 1;
$year = substr($ticketsLink, -$pos);
$pos = strpos($year, '/');
$year = substr($year, 0, $pos);
$years[] = $year;
}
出于本示例的目的,我保留代码以获取年份字符串和时间字符串完全相同,以表明问题并非如此。我已经浏览了上面的代码并尝试对其进行调试 - 唯一让它不起作用的是当我将year变量推送到years数组时。
---更新包含新信息-----
不幸的是,拆分URL以获取必要的信息是最好的方法 - URL来自CSV提要。
所以,在第一次foreach之后,然后只是为了测试,我在$ years数组中运行一个foreach循环 -
foreach($years as $year){
echo $year;
}
最终,$ years数组将传递给mySQL数据库,但就目前而言,我只是想确保我正确处理URL。结果循环看起来像这样:
2014 2015年 2014 2016
相反,我什么都没得到,并且在第一个foreach(我打破网址的地方)之后的所有代码都没有运行。我在底部有一个回声,回声"这段代码有效!",当我尝试将值推送到$ years数组时,它不会打印到屏幕上。