【问题标题】:Getting ID from array (PHP)从数组中获取 ID (PHP)
【发布时间】:2011-12-18 14:38:43
【问题描述】:

我有一个这样的数组:

Array
(
    [0] => Array
        (
            [0] => Sales
            [1] => Offices
            [2] => Products
        )
    [1] => Array
        (
            [0] => Cars
            [1] => Trucks
            [2] => Management
        )
)

所有这些“汽车”“卡车”等都是链接<a href="/mysite/catalog/63">Cars</a> 等。现在我需要从这些链接中获取 ID 号吗?但我对 PHP 很陌生,我不知道如何获得它。 Foreach 循环和重置功能或类似的东西?

如果需要这些信息,这在 drupal 和 ubercart 上。

谢谢。

【问题讨论】:

    标签: php arrays drupal ubercart


    【解决方案1】:

    像这样:

    foreach($yourarry as $arr2){
        foreach($arr2 as $id=>$text){
            echo $id;
            echo $text;
        }
    }
    

    【讨论】:

    • 此时 $text = 汽车。您需要explode() 或正则表达式来获取ID。
    • 谢谢,到目前为止,xplode() 遇到了一些问题。我注意到它实际上也打印了一些 html。基本上 $text 是这样的:汽车(以及它的 html:Cars/。我怎样才能从中获得 ID #32?
    【解决方案2】:

    我认为您正在寻找带有preg_matchforeach 循环 explode() 以提取ID:

    $regex = '/href="([^"]+)/i';
    foreach ($arr as $item) {
      foreach ($item as $html) {
        if (preg_match($regex, $html, $matches)) {
          $id = end(explode('/', $matches[1]));
          // For the string '<span class="field-content"><a href="/mysite/catalog/32">Cars/<a></span>' $id is equal to 32
        }
      }
    }
    

    【讨论】:

    • 谢谢克莱夫。这正是我正在寻找的。现在拿到身份证了:)
    【解决方案3】:

    a href="/mysite/catalog/63"

    ...暗示 63 是 Cars 的 id - 但在您的示例数组中既没有名为 id 的键,也没有 63 的值 - 您无法编写代码来查找不存在的值。

    如果你想从链接文本中提取数字,那么看看各种字符串解析函数,最容易使用的函数是 strtok、explode 或 preg_match。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-06
      • 2013-07-07
      • 2017-12-05
      • 2019-09-11
      • 2021-07-29
      • 2018-05-05
      • 1970-01-01
      相关资源
      最近更新 更多