0

我想在开始键之后迭代以下数组。

$array = array(
   'id' => '3',
   'update' => 'today',
   'create' => 'yesterday',
   'version' => 1,
   'start' => true,
   'key_1' => '1'
   'k2' => '2',
   'f2' => '4',
   .
   .
   .
   .
   -- more elements --
);

foreach ($array as $key => $value) { //I want to iterate after start element. 
    if (!empty($value)) {
        echo $key';
    }
}

在 php 中执行此操作的最佳方法是什么?

4

2 回答 2

0

使用切片方法:

// get an array of keys
$keys = array_keys($array);

// find `start`
$index = array_search('start', $keys);

// extract the section of the array after it
$slice = array_slice($array, $index + 1);

foreach($slice as $key => $value) {
    if(!empty($value)) {
        echo $key, ',';
    }
}

和迭代方法:

$found = false;
foreach($array as $key => $value) {
    if(!$found && $key == 'start') {
        $found = true;
    }
    else if($found && !empty($value)) {
        echo $key, ',';
    }
}
于 2013-09-21T04:05:34.930 回答
0

尝试这个:

$start = FALSE;
foreach ($array as $key => $value) {
    if ($key == 'start'){
        $start = TRUE;
    }
    if (!$start){
       continue; //have not reached start key, jump to the next iteration
     }
    if (!empty($value)) {
        echo $key;
    }
}
于 2013-09-21T03:42:01.193 回答