如何使用PHP循环使用foreach循环数组?

时间:2015-08-10 18:32:57

标签: php arrays foreach

我在while循环中,需要获取循环生成的数组中的一些数据。我的数组看起来像这样:

print_r($fields); //produces this

Array
(
    [0] => 5, - not set -
    [1] => 9, - not set -
    [2] => 10, - not set -
    [3] => 11, - not set -
    [4] => 14, - not set -
    [5] => 19, 12
    [6] => 20, mm_cb_on
    [7] => 21, - not set -
    [8] => 27, Noe
    [9] => 28, Pena
    [10] => 62, mm_cb_off
)
Array
(
    [0] => 5, Two Individuals
    [1] => 9, - not set -
    [2] => 10, - not set -
    [3] => 11, - not set -
    [4] => 14, - not set -
    [5] => 20, mm_cb_off
    [6] => 21, 1
    [7] => 27, SecPartF
    [8] => 28, SecPartL
    [9] => 30, testname3
    [10] => 31, last3
    [11] => 33, 
    [12] => 34, 
    [13] => 36, 
    [14] => 37, 
    [15] => 39, 
    [16] => 40, 
    [17] => 42, 
    [18] => 43, 
    [19] => 45, 
    [20] => 46, 
    [21] => 48, 
    [22] => 49, 
    [23] => 51, 
    [24] => 52, 
)
Array
(
    [0] => 5, - not set -
    [1] => 9, December
    [2] => 10, 4
    [3] => 11, 2014
    [4] => 12, 1915 Canterbury Street
    [5] => 13, Austin
    [6] => 14, Texas
    [7] => 15, 78702
    [8] => 19, 14
    [9] => 20, mm_cb_on
    [10] => 21, - not set -
    [11] => 62, mm_cb_off
)

每个键都有一个键和值本身如下:

foreach ($fields as $keys) {

    $key = explode(',', $keys);

}

我正在尝试为数组中的每个项设置值,但需要先检查是否存在某些内容。例如:

if ($key[0] == 19) {

    $prov_id = $key[1];

} else {

    $prov_id = '';

}

我遇到的问题是并非$ key [0]中的每个数组都有" 19" ...如果不存在,如何设置空值?我在搞什么?

2 个答案:

答案 0 :(得分:0)

也许您需要使用isset()检查该数组索引是否有值,如果没有,请设置默认值。

答案 1 :(得分:0)

清理数组仍然很好,使第一个标记化值只是数组的键,值只是值,不需要考虑爆炸。

无论如何,试试这个:

<?php
$uglyArray = ['1,', '2,notset','3,imaset'];

foreach ($uglyArray as $k => $v) {
      $parts = explode(',', $v);      
      var_dump($parts);
      if (empty($parts[1]) || $parts[1] == 'notset') {
        //not set
        $uglyArray[$k] = "{$parts[0]}, A new value";
      } else {
          //has value
          continue;
      }            
}

var_dump($uglyArray);
?>

<强>输出:

array(2) {
  [0]=>
  string(1) "1"
  [1]=>
  string(0) ""
}

array(2) {
  [0]=>
  string(1) "2"
  [1]=>
  string(6) "notset"
}

array(2) {
  [0]=>
  string(1) "3"
  [1]=>
  string(6) "imaset"
}


array(3) {
  [0]=>
  string(14) "1, A new value"
  [1]=>
  string(14) "2, A new value"
  [2]=>
  string(8) "3,imaset"
}

要清理,请考虑:

    $uglyArray = ['2,', '4,notset','6,imaset'];
    $cleanArray = [];
    foreach ($uglyArray as $k => $v) {
          $parts = explode(',', $v);                  
          if (empty($parts[1]) || $parts[1] == 'notset') {
            //not set
            $cleanArray[$parts[0]] = "A new value";
          } else {
              //has value
              $cleanArray[$parts[0]] = $parts[1];
              continue;
          }            
    }


 array(3) {
  [2]=>
  string(11) "A new value"
  [4]=>
  string(11) "A new value"
  [6]=>
  string(6) "imaset"
}