我只为我的画廊创建一个颜色提取器。对于每个图像,我在数据库中有一行用于颜色,这是数据库中这些行之一的一部分。
行示例:
CCCCCC,CCCCFF,99CCCC,333333,9999CC,999999,CCFFFF,000000,000033,669999,666699,333366,003333,336666,666666,FFFFFF,FF9900,333300...
我没有在这里添加所有颜色因为太长了。
现在,在照片页面中,我需要显示这些颜色,但不是全部。例如只有20种颜色。所以我写了这段代码:
$all_colors = $db->super_query("SELECT color
FROM colors
WHERE photo_id='{$photoid}'
");
$list = explode(',',$all_colors['color'], 20);//Select 20 colors
sort($list); //And sorting colors
foreach ($list as $item){
echo $item."<br>";
}
现在的问题是,这是该代码的结果:
000000
000033
003333
330000
333300
333333
333366
336666
663300
666633
666666
666699
669999
996633,FFFFCC,CC9966,CCCC99,663333,FF9933,FFCC66,CC9933,CC6600,666600,996600,003300,999966,FFCC33,CCFFCC,996666,999933,FFCC00,CC9999,FFFF99,FF9999
999999
9999CC
99CCCC
CCCCCC
CCCCFF
CCFFFF
您可以看到颜色太多的行!
结果必须如下:
000000
000033
003333
330000
333300
333333
333366
336666
663300
666633
666666
666699
669999
996633
999999
9999CC
99CCCC
CCCCCC
CCCCFF
CCFFFF
我如何修复此代码?
答案 0 :(得分:1)
使用array_slice()
提取数组的前20个元素。
$list = array_slice(explode(',',$all_colors['color'], 21), 0, 20);
print_r($list);
结果:
Array
(
[0] => CCCCCC
[1] => CCCCFF
[2] => 99CCCC
[3] => 333333
[4] => 9999CC
[5] => 999999
[6] => CCFFFF
[7] => 000000
[8] => 000033
[9] => 669999
[10] => 666699
[11] => 333366
[12] => 003333
[13] => 336666
[14] => 666666
[15] => FFFFFF
[16] => FF9900
[17] => 333333
[18] => 333366
[19] => 336666
)
答案 1 :(得分:1)
选项#1
$all_colors = $db->super_query("SELECT color
FROM colors
WHERE photo_id='{$photoid}'
ORDER BY color
LIMIT 20");
$list = explode(',',$all_colors['color']);
foreach ($list as $item){
echo $item."<br>";
}
选项#2
$all_colors = $db->super_query("SELECT color
FROM colors
WHERE photo_id='{$photoid}'");
$list = array_slice(explode(',',$all_colors['color']), 0, 20);//Select 20 colors
sort($list); //And sorting colors
foreach ($list as $item){
echo $item."<br>";
}
选项#3
$all_colors = $db->super_query("SELECT color
FROM colors
WHERE photo_id='{$photoid}'");
$list = explode(',',$all_colors['color'], 21);//Select 20 colors
if (count($list) == 21)
array_pop($list);
sort($list); //And sorting colors
foreach ($list as $item){
echo $item."<br>";
}
答案 2 :(得分:0)
试试这个:
$all_colors = $db->super_query("SELECT color
FROM colors
WHERE photo_id='{$photoid}'
");
//Select all colors, third parameter limits, but last one will be remaining string
$list = explode(',',$all_colors['color']);
sort($list); //And sorting colors
$c = 0;
foreach ($list as $item){
echo $item."<br>";
//if c equals 20 break
if($c==20)
break;
$c++;
}
Noe:这是快速建议,方法有效。我相信有更好的方法做同样的事情。