knot22 knot22 - 13 days ago 6
PHP Question

regex for _number

The following array is coming from $_POST for a PHP web app:

enter image description here

I'm trying to come up with a way to identify which of the keys ends with underscore and a number and then create a separate multidimensional array for those. Unfortunately, I'm stuck on the first step of identifying which of the keys ends with underscore and a number. Here is my experimental code:



foreach ($values as $k => $v):
echo $k . '-' . $v . '<br>';
preg_match_all('!\d+!', $v, $m);
echo '<pre>' . print_r($m, 1) . '</pre>';
// echo $m[$k];
endforeach;





And a partial screen shot of the result:

enter image description here

The end goal is to get something like this as the result:



[scenarioID] => 7
[comments] => test 1
[scenarioinserted] =>
Array
(
[0]=>Array
(
[itemID]=>100
[itemvalue]=>
),
[1]=>Array
(
[itemID]=>120
[itemvalue]=>
),
etc.



How can this be accomplished?

EDIT

Here was my attempt to set the HTML to
name="itemID[]"
in the PHP code:

foreach ($o as $key => $value):
foreach ($value as $k => $v):
if (!in_array($key, $calculation)):
if ($k === 'itemID'):
//$td[$key][$k] = '<input type="text" name="itemID_' . $i . '" style="width: 3em" readonly="readonly" value=' . $o[$key][$k] . '>';
$td[$key][$k] = '<input type="text" name="itemID[]" style="width: 3em" readonly="readonly" value=' . $o[$key][$k] . '>';
elseif ($k === 'itemvalue'):
$class = (!empty($errors[$k])) ? ' class="fail" ' : '';
$td[$key][$k] = '<input type="text" name="itemvalue[]" style="width: 7em"' . $readonly . $class . ' value="' . $o[$key][$k] . '">';
else:
$td[$key][$k] = $v;
endif;
else:
$td[$key][$k] = $v;
endif;
endforeach;
endforeach;


And a screen shot of the resulting HTML source code:
enter image description here

FURTHER EDIT

The above returns this:

enter image description here

Brilliant! Many thanks for the help. This is MUCH better than my original approach.

Answer

in the form use:

name="itemID[]"

and

name="itemvalue[]"

now you have nice arrays to use