Reputation: 2357
I have into $_POST array all the data i need.
If I print_r
the array, I see something like this:
Array (
[0_45_115] => 01
[0_46_115] => 01
[0_47_115] => 01
[0_48_115] => 01
[0_49_115] => 01
[0_50_115] => 01
[0_51_115] => 01
[0_52_115] => 01
[0_53_115] => 01
[0_54_115] => 01
[0_55_115] => 01
[0_56_115] => 01
[0_57_115] => 01
[0_58_115] => 01
[0_59_115] => 01
[0_60_115] => 01
[0_61_115] => 01
[0_62_115] => 01
[0_63_115] => 01
[0_64_115] => 01
[0_65_115] => 01
[0_66_115] => 01
[0_67_115] => 01
)
The index i post from the form (the name attr
) doesn't have underscores. For example:
<input type="text" name="0 45 115" value="" />
Let's forget this.
0_45_115
which the index is will provide me all the neccessery data I want to update or insert a new row into my database. The value will saw me the information I want.
The problem is that I don't know how to manage the array. Maybe I must use foreach
method, and the I will use split
function to split the index of each row. Then I will do all the other stuff for insertion/update my database.
I ask how can I use foreach
to take the info (index-data) from $_POST
array.
Upvotes: 0
Views: 2500
Reputation: 12993
See the array_keys() function.
It will return all the keys of the input array, than you can use the split() function to work on the keys and get the data you need.
For example:
$keys = array_keys($yourArray);
foreach($keys as $k) {
$data = split("_", $k);
print $data[0];
print $data[1];
print $data[2];
}
Upvotes: 1
Reputation: 77420
As an alternative to a loop, you can use array_map
:
array_map(function ($str) {return explode('_', $str);},
array_keys($_POST));
Result:
array (
array (
0 => '0',
1 => '45',
2 => '115',
),
array (
0 => '0',
1 => '46',
2 => '115',
),
array (
0 => '0',
1 => '47',
2 => '115',
),
...
Since only PHP 5.3 and newer have anonymous functions at the language level, a loop is the better choice if you need to support earlier PHP versions. Otherwise, you have to use create_function
, which is just ugly.
Upvotes: 0
Reputation: 57326
The spaces are converted to underscores per PHP specifications. See this page for more details. Specifically, search for this string in the page: Dots and spaces in variable names are converted to underscores.
I think the right approach would be
foreach($_POST as $key => $value)
{
$parts = explode('_', $key); //split your $key
//then deal with corresponding $value
}
Upvotes: 1
Reputation: 5042
foreach( $yourArray as $k => $v ) {
$keys = explode( "_", $k) // for first iterate you will get array('0','45','115')
}
Upvotes: 1