【问题标题】:PHP how to retrieve array valuesPHP如何检索数组值
【发布时间】:2011-04-06 15:27:24
【问题描述】:

我有以下数组,我想检索namecommenteach of the tags(插入数据库。我怎样才能检索数组值。另外,我可以只过滤大于的标签值吗? 3 个字符,仅包含 a-Z0-9 值。非常感谢。

Array
(
    [folder] => /test
    [name] => ajay
    [comment] => hello world.. test comment
    [item] => Array
        (
            [tags] => Array
                (
                    [0] => javascript
                    [1] => coldfusion
                )

        )

)

【问题讨论】:

  • 请参阅PHP manual,了解如何访问数组值。过滤可以通过regex
  • 您应该查看我提出的有关该主题的问题以及如何在不同的情况下使用它。

标签: php arrays


【解决方案1】:
$name = $array['name'];
$comment = $array['comment'];
$tags = $array['item']['tags']; // this will be an array of the tags

然后您可以遍历标签,例如:

foreach ($tags as $tag) {
  // do something with tag
}

或者单独访问每一个

echo $tags[0];
echo $tags[1];

【讨论】:

    【解决方案2】:
    $name = $array['name'];
    echo $name; // ajay
    
    $comment = $array['comment']
    echo $comment;  //hello world.. test comment
    
    $tags = $array['item']['tags'];
    echo $tags[0]; // javascript
    echo $tags[1]; // coldfusion
    

    http://www.php.net/manual/en/language.types.array.php

    【讨论】:

      【解决方案3】:

      要过滤超过 3 个字符且仅包含 a-z、A-Z、0-9 的标签,您可以使用此代码

      $alltags =  $your_array["item"]["tags"];
      
      $valid_tags = array();
      foreach($alltags as $tag)
        if ((preg_match("/^[a-zA-Z0-9]+$/", $tag) == 1) && (strlen($tag) > 3)) $valid_tags[] = $tag;
      

      像这样使用它

      print_r($valid_tags);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多