php解析数组值

时间:2012-05-04 14:58:24

标签: php arrays parsing

在阵列方面我不是很好所以这里可能非常简单但不适合我!我通过POST获取了一组值,我需要解析它们并将值存储在表中。我应该如何使用经典解析,例如:

foreach($array as $a) {
  $text = $a->text;
  $name = $a->user->name;
}

等解析一个如下所示的数组:

[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
)

4 个答案:

答案 0 :(得分:1)

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>';
    } 
  }
}

答案 1 :(得分:1)

if( isset($_POST['item']) && isset($_POST['item']['tags']) ){
  foreach($_POST['item']['tags'] as $tag){
    //do stuff...e.g.
    echo $tag;
  }
}

答案 2 :(得分:1)

看起来您的数组形状如下,请查看

$array = array( "item" => array( "tags" => array("Bluetooth", "Wifi", "USB" ) ) );
var_dump($array);

你会看到类似这样的东西

array(1) {
  ["item"]=>
  array(1) {
    ["tags"]=>
    array(3) {
      [0]=>
      string(9) "Bluetooth"
      [1]=>
      string(4) "Wifi"
      [2]=>
      string(3) "USB"
    }
  }
}

现在解析这个数组,

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"
    } 
}

我希望这能让你对阵列产生怀疑。

答案 3 :(得分:0)

你只是想把文字拿出去吗?试试这个。

foreach($array['item']['tags'] as $tag) {
   $text = $tag;
}
相关问题