問題描述
PHP Grid 類型 Array 獲取行或列 (PHP Grid type Array get row or column)
This may sound like a silly question and I'm not thinking hard enough,
Or its harder than i think...
Say i have a array of numbers like:
$table = array(
'5','2','1','4','4','4',
'1','2','4','2','1','1',
'3','4','3','1','4','4',
'1','4','2','S','4','4',
'1','2','4','2','1','1',
'5','2','6','4','8','1'
);
S = where I want to get either the row or column based on where "S" is.
I know i can get where S is.
by doing:
$start = array_search('S', $table);
The ''grid'' this array is based on,The S can can be anywhere.
And the grid itself can be different sizes length and width.
How would i go about getting the whole row or column.?
(IE:S is in column 3 : 4,2,1,S,2,4)
(IE:S is in row 3 : 1,4,2,S,4,4)
Just a hint in the right direction would be helpful, Don't need to go all out for me.
Or a idea on how to approach this.
參考解法
方法 1:
Okay, I guess you have the width you want to use stored somewhere! (And you don't want to use 2-dimensional arrays, check the other answer if you don't care, a 2-dimensional array makes a lot more sense in this case).
If you want to get the line, use $start
which is the position of S in the array and divide it by the width. Then you need to round down or up (depends on if you are starting to count at 0 or 1)
For column you need to do something similar, use $start % $width
here. (add 1 if you start counting at 1).
方法 2:
Here is a hint:
$table[] = array();
$table[][0] = array(5,2,1,4,5);
$table[][1] = array(1,5,2,3,3);
$table[][2] = array(1,2,'s',4,5);
You will need an array of arrays to have an x/y search.
Your x is the nth element in the outer array.
Your y is the nth element in the inner array.
方法 3:
You can search your string like 's' in array and find column and row of that :
$cols=5; // your columns count
$row=1;
$i=1;
$array = array('1','2','3','4','5','6','7','s','9');
foreach($array as $value)
{
if($value=='s')
{
echo 'Column : '.$i .' || Row : ' .$row ;
}
if($i==$cols)
{
$i=0;
$row++;
}
$i++;
}
(by AmyMarina、Jonas Osburg、Chris G.、M Rostami)