开发者

Add some logic in array filing

I'm trying to fill an array and I want to add some logic in it so it won't give me back errors...

Here is the code:

$entries_mixes = array();

foreach ($entries_query->result_array() as $entry) {


   $entries_mixes[] = array('title' => $entry['title'],
        'body' => $entry['body'],
        'author' => $entry['author'],
        'date_time' => $entry['date_time'],
        'id' => $entry['id'],
        'm开发者_如何学Cix_name' => $mix['name'],
        'photo_name' =>$photo['name']
    );


}

what I want to do is to be able to check if some of the variables exist before I put them into the array.... so for example if(isset($mix['name'])) then insert to array or else do nothing

The point is not having undeclared variables trying to be inserted to my array cause it gives back errors...thanks!


You can use the ? : ternary operator:

  $entries_mixes[] = array( 
       'title' =>  (isset($entry['title'])  ? $entry['title']  : null),
       'author' => (isset($entry['author']) ? $entry['author'] : null),
  ...

alternatively, use empty() for the check


You could use the ternary operator so that if the variables don't exist, NULL is used as the value. But you actually want to omit certain keys from the array altogether in that case. So just set each key separately:

$entry[] = array();
...
if (isset($mix['name'])) {
    $entry['mix_name'] = $mix['name'];
}
...
$entries_mixes[] = $entry;


The following will check if title doesn't exists in the entry array or if it's blank. If so, it'll skip the entry completely and continue to the next element in the loop.

$entries_mixes = array();

foreach ($entries_query->result_array() as $entry) {
  if (empty($entry['title'])) {
    continue;
  }

  $entries_mixes[] = array('title' => $entry['title'],
    'body' => $entry['body'],
    'author' => $entry['author'],
    'date_time' => $entry['date_time'],
    'id' => $entry['id'],
    'mix_name' => $mix['name'],
    'photo_name' =>$photo['name']
  );

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜