遍历特殊条件的数组

时间:2019-05-29 04:31:52

标签: php arrays

我想用if语句为我保存一些代码,所以我在这里做一个循环。

如何在不创建新数组的情况下执行以下操作?我想继续依靠第一个$ arr

这是一个简单的示例,我的数组实际上比那要大得多:)因此,请记住这一点,我必须检查名字项,然后再执行某些操作。

$arr = ['man_firstname', 'man_lastname', 'woman_firstname', 'woman_lastname'];

// just making sure the value from db is set 
// otherwise set it to an empty string
foreach ($arr as $item) {
    isset($db[$item]) ? $$item = $db[$item] : $$item = '';
}

// with that loop I have now $man_firstname, $man_lastname, $woman_firstname
// and $woman_lastname  are all set to their db values or are empty

// now I want to echo both first name 
// and last name of the man and woman but ONLY WHEN THEIR FIRST NAMES IS NOT EMPTY

foreach (?? as ??) {
    if (!empty(firstname)) {
        // echo both first name and last name
    }
}

// desired results: echo "john doe" only if firstname of the man is set, 
// the same with "jenna smith" if her first name is not set then do 
// nothing with her array item```

1 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,则需要这样的东西:

$arr = ['john', 'doe', 'john', '', 'jenna', 'smith', '', 'smith'];

if (count($arr) % 2) {
   throw new Exception('Missing person name / surname !');
}

for ($i=0; $i < count($arr); $i+=2) {
   if ($arr[$i] && $arr[$i+1]) {
      echo "{$arr[$i]} {$arr[$i+1]}<br>";
   }
}

顺便说一句,请记住,数组中的名称和姓氏应为偶数-否则,您将不知道缺少的内容-名称或姓氏以及缺少的人。这就是为什么我在这种情况下添加了异常生成的原因。