根据数组中的重复ID创建二进制文件

时间:2019-09-04 18:51:21

标签: php arrays binary

我有一个image_ID数组,其中一些重复出现。我想将它们与彩色行组合在一起(我正在使用粗体以查看效果)。我不能使用奇数/偶数,因为image_id可能与偶数相邻。这是一个示例数组;

  

数组(1 => 9681 2 => 9681 [3] => 9681 [4] => 8351 [5] => 8351   [6] => 8351 [7] => 2320 [8] => 2320 [9] => 2320 [10] => 2320 [11] =>   2320 [12] => 20711 [13] => 20711 [14] => 20711 [15] => 20711 [16] =>   5223 [17] => 5223 [18] => 5223 [19] => 5223 [20] => 5223)

这个想法是9681s将是一种颜色,然后8351s将是另一种颜色,然后2320s可以重新启动与9681s相同的颜色。为每个图像创建可见的分组(基于image_ID)。图像_ID是唯一可用于对图像进行分组的东西。

所以问题的症结在于如何将事物分组到列表或数组中(如果我必须在它们之间进行转换,我可以)并将替代格式应用于每组。如果该替代格式是对我有用的二进制格式,那么上面的内容将是“ 11100011111000011111”,因为我可以在循环中使用该格式以应用if ... else循环并使用某些样式。

我尝试过     如果($ image_id&2){     ...应用粗体     }其他{     ...不要大胆     }

table of images with tags

//这是我最后使用的代码,感谢@kainaw

// Create a binary pattern to match occurrence of image_id for visually grouping later 
// Create a new array to count the values then make the count the keys
$output_result_array['bin_group'] = array_flip(array_count_values($output_result_array['source']));
// Setup temp variables
$c = false;
$l = null;
// Loop though the counted and flipped array creating a binary representation of groups.    
foreach($output_result_array['source'] as $k=>$v) {
   if($v != $l) $c = !$c;
   $output_result_array['bin_group'][$k] = $c;
   $l = $v;
}
// START add different row colouring based on Image_id groups represented in BIN        
if ($output_result_array['bin_group'][$x]) {
$output_result .= '<tr class="post bg2;">';
}   else {
$output_result .= '<tr>';
}
// END add different row colouring  

Now with grouped row colouring

1 个答案:

答案 0 :(得分:1)

您需要一个布尔数组。那很容易。我要做的是创建一个单独的数组。假设$ a是您的数组。首先,创建一个新数组,其中的键是$ a的值:

$b = array_flip($a);

现在,$ a中的每个值都是$ b中的键。 $ b中的值是每个值出现在$ a中的次数的计数。我们不在乎。

下一步是替换布尔值。从等于您不想开始的任何事物开始。然后,在每次使用时将其反转。

$c = false;
foreach($b as $k=>$v) $b[$k] = $c = !$c;

您将$ c设置为等于$ c的负数。该新值将传递到二进制数组中。您最终得到一个数组,其中每个键都是您的原始值,每个值都是一个交替的布尔值。

您如何使用它?考虑一下。我原来的数组是$ a,而$ b是我的布尔数组。

foreach($a as $v) {
  if($b[$v]) print "$v is true.\n";
  else print "$v is false.\n";
}

如果不是,您只需要一个布尔数组。这也很容易做到。同样,假设您的原始数组是$ a,而新的布尔数组是$ b。关键是存储最后看到的值。

$b = array();
$c = false;
$l = null;
foreach($a as $k=>$v) {
  if($v != $l) $c = !$c;
  $b[$k] = $c;
  $l = $v;
}

每次最后一个值与新值都不匹配时,布尔值就会被翻转。