-1

I have an array like this:

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

All those 'Cars' 'Trucks' etc are links <a href="/mysite/catalog/63">Cars</a> etc. Now I would need to get that ID number of from those links? But Im pretty new to PHP and I have no idea how to get it. Foreach loop and reset function or something similar?

This is on drupal and ubercart if those info is needed.

Thanks.

nfechner
  • 17,295
  • 7
  • 45
  • 64
user995317
  • 353
  • 6
  • 16

3 Answers3

2

Like this:

foreach($yourarry as $arr2){
    foreach($arr2 as $id=>$text){
        echo $id;
        echo $text;
    }
}
chown
  • 51,908
  • 16
  • 134
  • 170
Moe Sweet
  • 3,683
  • 2
  • 34
  • 46
  • at this point $text = Cars. You'll need to explode() or regex to get the ID. – Moe Sweet Oct 31 '11 at 09:44
  • Thanks, got so far but having some trouble with xplode(). I noticed that it actually print some html too. Basically the $text is something like this: Cars (and the html for it: Cars/. How can I get that ID #32 from that? – user995317 Oct 31 '11 at 10:47
1

I think you're looking for a foreach loop with a preg_match and explode() to extract the 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
    }
  }
}
Clive
  • 36,918
  • 8
  • 87
  • 113
0

a href="/mysite/catalog/63"

...implies that 63 is the id for Cars - but there is neither a key called id in your sample array nor a value of 63 - you can't write code to find a value which is not there.

If you want to extract the number from the link text, then have a look at the various string parsing functions, the easiest functions to use would be strtok, explode or preg_match.

symcbean
  • 47,736
  • 6
  • 59
  • 94