Reputation: 6672
I'm not very good when it comes to arrays so here's probably something very simple but not for me! I'm getting an array of values via POST and I need to parse them and store the values in a table. How should I use the classic parsing such as:
foreach($array as $a) {
$text = $a->text;
$name = $a->user->name;
}
etc to parse an array looking like this:
[item] => Array
(
[tags] => Array
(
[0] => Bluetooth
[1] => WiFi
[2] => USB
)
)
This is the entire POST array:
Array
(
[prodid] =>
[Submit] => Save
[productcode] => 797987
[cat_id] => 66
[brand] => Fysiomed
[name] => asdc asdc asd c
[productnew] => yes
[item] => Array
(
[tags] => Array
(
[0] => Bluetooth
[1] => WiFi
[2] => USB
)
)
[size] => 1
[barcode] => 7979871
[price] => 233.00
[priceoffer] => 0.00
[stock] => 50
[weight] => 0.30
[orderby] => 1
)
Upvotes: 1
Views: 39688
Reputation: 1241
Are you just trying to get the text out? try this.
foreach($array['item']['tags'] as $tag) {
$text = $tag;
}
Upvotes: 1
Reputation: 13985
Looks like your array is shaped like this, check this
$array = array( "item" => array( "tags" => array("Bluetooth", "Wifi", "USB" ) ) );
var_dump($array);
You will see something like this
array(1) {
["item"]=>
array(1) {
["tags"]=>
array(3) {
[0]=>
string(9) "Bluetooth"
[1]=>
string(4) "Wifi"
[2]=>
string(3) "USB"
}
}
}
Now for parsing this array,
foreach($array as $in => $val) {
// as $array has key=>value pairs, only one key value pair
// here $in will have the key and $val will have the value
// $in will be "item"
print $in; // this will print "item"
foreach($val as $in2 => $val2 ){
// only one key : "tags"
print $in; // this will print "tags"
print $val2[0]; // this will print "Bluetooth"
print $val2[1]; // this will print "Wifi"
}
}
I hope this clears you doubt regarding arrays.
Upvotes: 1
Reputation: 1299
if( isset($_POST['item']) && isset($_POST['item']['tags']) ){
foreach($_POST['item']['tags'] as $tag){
//do stuff...e.g.
echo $tag;
}
}
Upvotes: 2
Reputation:
if(isset($_POST) && !empty($_POST)) {
foreach($_POST as $key => $value) {
if($key == 'item') {
echo $value[$key]['tag'][0]. '<br>';
echo $value[$key]['tag'][1]. '<br>';
echo $value[$key]['tag'][2]. '<br>';
}
}
}
Upvotes: 1