0

我只是为我的画廊创建一个颜色提取器。对于每个图像,我在数据库中都有一行颜色,这是数据库中这些行之一的一部分。

行示例:

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

我该如何修复此代码?

4

3 回答 3

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
)
于 2013-07-26T19:29:22.943 回答
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>";
}
于 2013-07-26T19:34:51.723 回答
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:这是一个快速的建议,有效的方法。我相信有更好的方法来做同样的事情。

于 2013-07-26T19:34:30.110 回答