我有一个像这样的数组
array:32 [▼
"ID" => "7917"
"ProvinceCode" => "MB"
"Create" => "2016-05-18 18:16:26.790"
"DayOfTheWeek" => "4"
"Giai1" => "28192"
"Giai2" => "83509"
"Giai3" => "51911-02858"
"Giai4" => "14102-97270-96025-08465-89047-45904"
"Giai5" => "7892-9140-4069-8499"
"Giai6" => "6117-7471-5541-9119-4855-0566"
"Giai7" => "843-860-023"
"Giai8" => "71-13-55-89"
"Giai9" => ""
"Status" => "1"
]
我有一个int变量$position = 59
,我的工作是通过计算来自Giai1 to Giai9
的{{1}}来自59 times
的字符来查找值,并获得此位置的值不包含字符0
,如果-
,那么位置$position = 59
的获取值将会返回。
例如,在58
位置找到值,返回值为20
我已经编写了这段代码来执行此操作
1 at 14102 in Giai4 (actually 19 count from 0)
预期结果将返回带有getted number标记的数组。
例如,代码在位置$position = 59;
$count = 0;
foreach ($data['result'][0] as $key => $item)
{
if(preg_match('@Giai@s', $key))
{
$_item = str_replace('-', '', $item);
$count = $count + strlen($_item);
$chars = str_split($item);
$chars_sp = array_count_values($chars);
$countChar = count($chars);
if($count > $position)
{
//this block contains needed position
$math = $count - $position;
$secmath = strlen($_item) - $math;
for($i=$secmath;$i>=0;$i--){
if($chars[$i] == '-'){
$splash_last++;
}
}
$secmath = $secmath + $splash_last;
if($chars[$secmath] == '-'){
echo "+1 - ";
$secmath = $secmath + 1;
}
echo "Count: $count Match: $math Secmatch: $secmath Splash_last: $splash_last";
$chars[$secmath] = 'x' . $chars[$secmath] . 'y';
$edited = implode('', $chars);
$data['result'][0][$key] = $edited;
break;
}
}
}
dd($data['result'][0]);
}
找到了数字,并在59 (58 from 0)
处首先签名,在x
处签署。您可以在y
Giai5
从1到50它工作正常,但在位置50之后,我得到的位置值总是错误的
有什么想法吗?
答案 0 :(得分:0)
您可以通过一个简单的array_grep()
来获取所有" Giai"键和implode
将值连接到一个大字符串,然后选择该字符串的位置。
$giai = array_flip(preg_grep("/^Giai\d+$/", array_flip($a)));
echo implode("",$giai)[$pos];
答案 1 :(得分:0)
如果我这次理解正确,你可以这样做:
$array = [
"ID" => "7917",
"ProvinceCode" => "MB",
"Create" => "2016-05-18 18:16:26.790",
"DayOfTheWeek" => "4",
"Giai1" => "28192",
"Giai2" => "83509",
"Giai3" => "51911-02858",
"Giai4" => "14102-97270-96025-08465-89047-45904",
"Giai5" => "7892-9140-4069-8499",
"Giai6" => "6117-7471-5541-9119-4855-0566",
"Giai7" => "843-860-023",
"Giai8" => "71-13-55-89",
"Giai9" => "",
"Status" => "1"
];
$position = 59;
$start = 0;
$end = 0;
foreach ($array as $key => &$value) {
if (!preg_match('/Giai/', $key)) {
continue;
}
$start = $end + 1;
$end = $start + strlen(str_replace('-', '', $value)) - 1;
if (($start <= $position) && ($position <= $end)) {
$counter = $start;
$value = str_split($value);
foreach ($value as &$char) {
if ($char === '-') {
continue;
}
if ($counter === $position) {
$char = "x{$char}y";
break;
}
$counter++;
}
$value = join($value);
}
}
var_dump($array);
这是amalgamation。
代码有点冗长,但这是因为当你观察位置时你会跳过破折号(-
),但是当你需要标记角色时你需要将它们带入帐户。从这段代码中你可以理解算法,然后按照你想要的方式重构代码。我建议从嵌套循环中逃脱,因为它们很难阅读。您可以通过将代码分解为函数或使用可用的数组函数来完成此操作。