欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

foreach 追加有关问题,求高手帮忙看看

程序员文章站 2022-05-27 11:20:00
...
foreach 追加问题,求高手帮忙看看。

$citycode = array(
"北京"=>"101010100",
"朝阳"=>"101010300"
);

foreach ($citycode as $arr => $value) {
$citycode[$arr] = "http://weather.xxx.com/".substr($citycode[$arr], 3,4).".txt";
//$citycode[$arr] .= "http://weather.xxx.com/".$citycode[$arr].".txt";
}

/*
功能:按行保存为文件
*/

saveFile('api/weather.txt',implode("\r\n",$citycode));


?>


我想根据数组保存为换行文件,如下:
http://weather.xxx.com/0101.txt
http://weather.xxx.com/101010100.txt
http://weather.xxx.com/0103.txt
http://weather.xxx.com/101010300.txt

要怎么做?
我现在只能做到:
http://weather.xxx.com/0101.txt
http://weather.xxx.com/0103.txt

怎么追加进去呢?
------解决思路----------------------

foreach ($citycode as $arr => $value) {
$citycode[$arr] = "http://weather.xxx.com/".substr($citycode[$arr], 3,4).".txt";
//$citycode[$arr] .= "http://weather.xxx.com/".$citycode[$arr].".txt";
}

你这样明显的用t同样的键值覆盖了之前的值嘛,要不就换个键值如

$citycode[$arr.'1'] = "http://weather.xxx.com/".substr($citycode[$arr], 3,4).".txt";

------解决思路----------------------


$citycode = array(
"北京"=>"101010100",
"朝阳"=>"101010300"
);

$tmp = array();

foreach ($citycode as $arr => $value) {
$tmp[] = "http://weather.xxx.com/".substr($value, 3,4).".txt";
$tmp[] = "http://weather.xxx.com/".$value.".txt";
}

echo implode("\r\n", $tmp);

//saveFile('api/weather.txt',implode("\r\n",$citycode));



http://weather.xxx.com/0101.txt
http://weather.xxx.com/101010100.txt
http://weather.xxx.com/0103.txt
http://weather.xxx.com/101010300.txt


楼主是想这样么?
------解决思路----------------------
$citycode[$arr] .= "http://weather.xxx.com/".$citycode[$arr].".txt";
这里的$citycode[$arr] 已经被修改了
被上一句$citycode[$arr] = "http://weather.xxx.com/".substr($citycode[$arr], 3,4).".txt";

另外:$citycode[$arr] .= "http://weather.xxx.com/".$citycode[$arr].".txt";
使用拼接的话你忘记换行了。

改这样就可以了

$citycode = array(
"北京"=>"101010100",
"朝阳"=>"101010300"
);

$result = array();

foreach ($citycode as $arr => $value) {
array_push($result,"http://weather.xxx.com/".substr($value, 3,4).".txt");
array_push($result,"http://weather.xxx.com/".$value.".txt");
}

/*
功能:按行保存为文件
*/

saveFile('api/weather.txt',implode("\r\n",$result));


http://weather.xxx.com/0101.txt
http://weather.xxx.com/101010100.txt
http://weather.xxx.com/0103.txt
http://weather.xxx.com/101010300.txt
foreach 追加有关问题,求高手帮忙看看

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。

相关文章

相关视频