PHP foreach内部循环在循环内添加

时间:2015-10-30 07:15:17

标签: php arrays foreach

我是php新手,我在阵列上练习。

我在一些转换为数组的字符串上创建了一个foreach,然后在foreach中我在循环结束前添加了2个数组,一个随机。

这里是代码:

<?php
   //Some string to practice on
      $links = " http://hi.co.il<br>
        ??????  ht tp://hi.co.il<br>
   ????? http://hi.co.il<br>
   http://hi.co.il<br>
   http://hi.co.il<br>
   http://mega.co.il<br>
   http://hi.co.il";

   $links = explode('<br>',trim($links));


   $currenturl = array("http://mega.co.il","http://mega.co.il/","http://mega.co.il/#");

$i = 0;
$len = count($links);
$rand = rand(0,$len-1);

foreach($links as $key => $value) {
   $i++;//Practice counter

   $value = preg_replace('/\s+/', '', $value);//Clean all whitespaces
   $links[$key] = strstr($value, 'http');//Cut the value from the left and return only the right.

    if(in_array($value,$currenturl)) {
        unset($links[$key]);
    }

    //Practice to my self

    if(is_array($value) == false){
       $links[$rand] = array("dfd","dfdf","dfdf");
    }

   //just a practice to add a array to a value before the end of the loop.
   if($i == $len-2){
       $links[$key] = array( array("rose", 1.25 , 15),
                             array("daisy", 0.75 , 25),
                             array("orchid", 1.15 , 7) 
                           ); 
   }


     //Not working , this is the main question how to foreach on value that is a array
     if(is_array($value)){
              foreach($value[$key] as $key => $val){
                  echo 'this is second foreach echo';
                   echo $val;
               }
         }

}

$links = array_filter($links);// Clean empty array values
$links = array_values($links);//Reindex array keys

   echo '<pre>';
   print_r($links);
   echo '</pre>';



   ?>

此输出:

Array
(
    [0] => http://hi.co.il
    [1] => Array
        (
            [0] => dfd
            [1] => dfdf
            [2] => dfdf
        )

    [2] => http://hi.co.il
    [3] => http://hi.co.il
    [4] => Array
        (
            [0] => Array
                (
                    [0] => rose
                    [1] => 1.25
                    [2] => 15
                )

            [1] => Array
                (
                    [0] => daisy
                    [1] => 0.75
                    [2] => 25
                )

            [2] => Array
                (
                    [0] => orchid
                    [1] => 1.15
                    [2] => 7
                )

        )

    [5] => http://hi.co.il
)

为什么is_array($ value)没有工作的问题,因为即使值是数组,它总是返回false? 我如何foreach和我在循环中添加的数组? 可能吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

is_array返回false,因为$ value是字符串,而不是数组。