我有一个像这样结构的数组:
<?php
$orderdata = array(
"service_type_web" => "on",
"custid" => "A12345",
"domain_web" => "foo.com",
"cust_email_web" => "foo@bar.com",
"plantype" => "dynamic",
"platform" => "unix",
"service_type_ssl" => "on",
"custid" => "A23456",
"common_name" => "foo.bar.com",
"cust_email_ssl" => "bar@foo.com"
);
?>
我需要做的是找到数组的service_type_ *部分,然后回显所有键值对,直到它到达下一个service_type_ *,然后循环中断。
现在这对于静态数据集很容易,但是数组可以改变大小,每个表单都可以根据不同的变量而改变,这就是service_type_ *键值条目存在的原因。
任何想法都会受到赞赏。
编辑澄清:
我基本上需要这样,如果我需要,例如,网页托管的表单数据,它会找到service_type_web键并返回以下内容:
"service_type_web" => "on",
"custid" => "A12345",
"domain_web" => "foo.com",
"cust_email_web" => "foo@bar.com",
"plantype" => "dynamic",
"platform" => "unix",
......然后离开了:
"service_type_ssl" => "on",
"custid" => "A23456",
"common_name" => "foo.bar.com",
"cust_email_ssl" => "bar@foo.com"
第二次编辑:
好的,我快到了。我想出了以下内容:
$delimiter = 0;
$array_counter = 0;
foreach($orderdata as $orderkey => $ordervalue) {
if($orderkey == "service_type_web") {
$new_array = array_slice($orderdata, $array_counter);
$array_counter ++;
$delimiter = 1;
} elseif(preg_match('/service_type_[a-z\_]+/', $orderkey)) {
if($delimiter == 1) {
echo $orderkey . " => " . $ordervalue . "<br />\n";
break;
}
} else {
$array_counter ++;
}
}
然而if语句中的中断不起作用,即使我得到它来回显当前数组指针的键/值对,它回声
"service_type_ssl" => "on"
任何人都知道为什么?有点难过。
答案 0 :(得分:0)
您可以查看&#34; key&#34;在使用array_key_exists
进入循环之前$orderdata = array(
"service_type_web" => "on",
"custid" => "A12345",
"domain_web" => "foo.com",
"cust_email_web" => "foo@bar.com",
"plantype" => "dynamic",
"platform" => "unix",
"service_type_ssl" => "on",
"custid" => "A23456",
"common_name" => "foo.bar.com",
"cust_email_ssl" => "bar@foo.com"
);
if (array_key_exists('service_type_web', $orderdata )) {
echo "array found";
}
答案 1 :(得分:0)
可能的解决方案是。这个答案可能会指导您正确的方向,但您仍然需要做一些小的改动。
$input = array(
"service_type_web" => "on",
"custid" => "A12345",
"domain_web" => "foo.com",
"cust_email_web" => "foo@bar.com",
"plantype" => "dynamic",
"platform" => "unix",
"service_type_ssl" => "on",
"custid" => "A23456",
"common_name" => "foo.bar.com",
"cust_email_ssl" => "bar@foo.com"
);
function preg_grep_keys($pattern, $input, $flags = 0) {
return array_intersect_key($input, array_flip(preg_grep($pattern, array_keys($input), $flags)));
}
$a = preg_grep_keys("/service_type_[a-z]*/", $input);
print_r($a);
预期输出
Array ( [service_type_web] => on [service_type_ssl] => on )