从数组中获取ID(PHP)

时间:2011-10-31 09:34:42

标签: php arrays drupal ubercart

我有一个这样的数组:

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上。

感谢。

3 个答案:

答案 0 :(得分:2)

像这样:

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

答案 1 :(得分:1)

我认为您正在寻找一个foreach循环,其中包含preg_match 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
    }
  }
}

答案 2 :(得分:0)

  

a href =“/ mysite / catalog / 63”

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

如果你想从链接文本中提取数字,那么看一下各种字符串解析函数,最简单的函数就是strtok,explode或preg_match。