当我在$ _POST上执行print_r时,我有一个可能如下所示的数组:
Array
(
[action] => remove
[data] => Array
(
[row_1] => Array
(
[DT_RowId] => row_1
[name] => Unit 1
[item_price] => 150.00
[active] => Y
[taxable] => Y
[company_id] => 1
)
)
)
row_1值可以是任何格式化为行_?
的值我希望这个数字是一个字符串,无论数字是多少。如果有帮助,该键和DT_RowID值将始终相同。
现在我正在这样做,但这似乎是一种不好的方式:
//the POST is a multidimensinal array... the key inside the 'data' array has the id in it, like this: row_2. I'm getting the key value here and then removing the letters to get only the id nummber.
foreach ($_POST['data'] AS $key => $value) {
$id_from_row_value = $key;
}
//get only number from key = still returning an array
preg_match_all('!\d+!', $id_from_row_value, $just_id);
//found I had to use [0][0] since it's still a multidimensional array to get the id value
$id = $just_id[0][0];
它可以工作,但我猜这是从$ _POST数组中获取该数字的更快方法。
答案 0 :(得分:0)
<?php
$array = [
'data' => [
'row_1' => [],
'row_2' => [],
]
];
$nums = [];
foreach ($array['data'] as $key => $val) {
$nums[] = preg_replace('@[^\d]@', '', $key);
}
var_export($nums);
输出:
array (
0 => '1',
1 => '2',
)
答案 1 :(得分:0)
请记住,preg_match
中使用的正则表达式不是最快的解决方案。我要做的是将字符串分割为_
并取第二部分。像那样:
$rowId = explode("_", "row_2")[1];
并将其放入循环中以处理所有元素。