我正在尝试获取包含x / y坐标和方向信息(跨越或向下)的数据数组,并使用递增数字链接共享单元格。这是一个填字游戏。这是原始数组:
Array
(
[0] => Array
(
[id] => 1
[puzzle_id] => 1
[word] => hello
[hint] =>
[direction] => across
[grid_x] => 3
[grid_y] => 1
)
[1] => Array
(
[id] => 2
[puzzle_id] => 1
[word] => loot
[hint] =>
[direction] => down
[grid_x] => 5
[grid_y] => 1
)
[2] => Array
(
[id] => 3
[puzzle_id] => 1
[word] => hellotest
[hint] =>
[direction] => down
[grid_x] => 3
[grid_y] => 1
)
[3] => Array
(
[id] => 4
[puzzle_id] => 1
[word] => looking
[hint] =>
[direction] => across
[grid_x] => 3
[grid_y] => 3
)
)
我想为每个名为“num”的条目添加一个新密钥,该密钥将从1开始并递增1,但是如果它们共享一个起始单元格,那么我需要跨越AND并分享相同的数字(共享一个grid_x和grid_y)。这是我现在的代码,但它没有产生我正在寻找的正确数字。
$puzzle_data2 = $puzzle_data;
$across_counter = 1;
foreach($puzzle_data as $rkey=>$row)
{
if($row['direction'] == 'across')
{
$puzzle_data[$rkey]['num'] = $across_counter++;
foreach($puzzle_data2 as $rkey2=>$row2)
{
if($row['direction'] == 'down')
{
if($row['grid_x'] == $row2['grid_x'] && $row['grid_y'] == $row2['grid_y'])
{
$puzzle_data[$rkey2]['num'] = $across_counter;
break;
}
}
}
}
}
foreach($puzzle_data as $rkey=>$row)
{
if(!isset($row['num']))
{
$puzzle_data[$rkey]['num'] = $across_counter++;
}
}
我最终得到了这个结果:
Array
(
[0] => Array
(
[id] => 1
[puzzle_id] => 1
[word] => hello
[hint] =>
[direction] => across
[grid_x] => 3
[grid_y] => 1
[num] => 1
)
[1] => Array
(
[id] => 2
[puzzle_id] => 1
[word] => loot
[hint] =>
[direction] => down
[grid_x] => 5
[grid_y] => 1
[num] => 3
)
[2] => Array
(
[id] => 3
[puzzle_id] => 1
[word] => hellotest
[hint] =>
[direction] => down
[grid_x] => 3
[grid_y] => 1
[num] => 4
)
[3] => Array
(
[id] => 4
[puzzle_id] => 1
[word] => looking
[hint] =>
[direction] => across
[grid_x] => 3
[grid_y] => 3
[num] => 2
)
)
我正在寻找ID 1和3都是“1”。如果你想到一个填字游戏,其中一个向下和跨越共享相同的起始单元格,在横向和向下键中用相同的数字标记,这就是我试图用我的数据集完成的。
感谢您的时间。
答案 0 :(得分:0)
您应该首先对数据进行排序,以便在向下移动到下一行之前,左上角的条目是第一个,跨越该行。 IE是我们阅读的方式。
我们可以使用grid_x和grid_y并计算哪个是第一个。
然后我们可以使用它们对数据进行排序。
function cmp($a, $b)
{
$a_index=($a['grid_y']*100)+$a['grid_x'];
$b_index=($b['grid_y']*100)+$b['grid_x'];
if ($a_index == $b_index)
{
return 0;
}
return ($a_index < $b_index) ? -1 : 1;
}
usort($puzzle_data, "cmp");
我在这里使用了100来简化操作,但你应该使用网格的宽度来提高准确性。
x1,y1会给出101
x3,y1会给出103
x1,y3会给301
y3,y3会给出303
所以订单将是101,103,301,303
然后使用grid_x和grid_y将数字应用于数据,以测试是否已完成。
$number=1;
$grid_numbers=array();
foreach($puzzle_data as $rkey=>$row)
{
if(isset($grid_numbers[$row['grid_x']][$row['grid_y']]))
{
$puzzle_data[$rkey]['num'] = $grid_numbers[$row['grid_x']][$row['grid_y']];
}
else
{
$grid_numbers[$row['grid_x']][$row['grid_y']]=$number;
$puzzle_data[$rkey]['num']=$number;
$number++;
}
}
那应该是一切