Foreach 循环是遍历数据的最佳方式。如果您想让您的代码更漂亮,请尝试使用三元版本
<?php foreach($query as $record) : ?>
<?php foreach($record as $field => $value) : ?>
*Things that need to be done on each field-value pair*
<?php endforeach; ?>
*Things that need to be done on each row*
<?php endforeach; ?>
此外,就像上面评论中提到的那样,在数据库中存储 ~ 分隔数据时会丢失很多功能。如果必须这样做,您可以尝试存储序列化对象而不是分隔字符串。您可以通过多种方式操作对象,例如json_encode()和json_decode()
$myArray = array();
$myArray['User1']['book'] = 'Pride and Prejudice';
$myArray['User1']['favorites'] = 'Water skiing';
$myArray['User2']['book'] = 'Mansfield Park';
$myArray['User2']['favorites'] = array('skateboarding', 'surfing', 'running');
$myArray['description'] = 'Things people like.';
echo '<pre>';
print_r(json_encode($myArray)); //This will convert your array to a string for the db
echo '</pre>';
echo '<pre>';
$myArrayString = json_encode($myArray);
print_r(json_decode($myArrayString)); //This will convert the db string to an object for manipulation
echo '</pre>';