在foreach循环内添加循环的PHP 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和我加入循环内的数组? 这是可能的 ?

谢谢 。


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

链接地址: http://www.djcxy.com/p/53021.html

上一篇: PHP foreach inside loop on array that added inside the loop

下一篇: Foreach loop not updating the values