-3
<?php
  $categories = [ 
          133   => 'Siomay',
          123   => 'Indonesian',
          20    => 'Bento',
  ];

  $input_categories = [
               'Siomay',
               'Indonesian',
               'Bento',
               'Yoghurt',
  ];

How to get id categories? The example shown

Results:

133
123
20
-1 // Miss (-1)
Alexander Farber
  • 21,519
  • 75
  • 241
  • 416
ratscoder
  • 13
  • 7

4 Answers4

1

To get the IDs in a loop:

foreach($categories as $key=>$value)
{
    echo $key . "<br />";
}

That will output

133
123
20
Matt
  • 2,851
  • 1
  • 13
  • 27
1

I assume you should show -1 when there is no appropriate value? If it's all about, try this:

<?php
  $categories = [ 
          133   => 'Siomay',
          123   => 'Indonesian',
          20    => 'Bento',
  ];

  $input_categories = [
               'Siomay',
               'Indonesian',
               'Bento',
               'Yoghurt',
  ];


foreach($input_categories as $input_category)
{
    if(in_array($input_category, $categories))
        echo array_search($input_category, $categories).'<br/>';
    else
        echo '-1<br/>';
}

Output:

133
123
20
-1
aslawin
  • 1,981
  • 16
  • 22
  • You should use a counter and print it after the foreach, so it will print the real number of miss – jonystorm Mar 11 '16 at 07:52
  • Hmm... I don't understand what do you mean.. Could you explain? – aslawin Mar 11 '16 at 07:55
  • The arrays he gave were an example, so with the previous code it would print: -1
    -1
    if there were 2 missing categories, this way at the end prints the amount of missing categories.
    – jonystorm Mar 11 '16 at 07:57
  • @jonystorm, ut where OP wrote information about counting missing categories? – aslawin Mar 11 '16 at 07:59
  • 1
    I missed the '-' sign on: echo '-'.$counter Since there is lack of information, my impression was that he wanted the amount of missing cats, but I can see also that he may not. He should be more explicit – jonystorm Mar 11 '16 at 08:04
  • if 133 => 'Siomay / Waffles / Crepes' ? should not min – ratscoder Mar 11 '16 at 08:05
0
foreach ( $categories as $k => $v ) {
    echo $k;    echo "<br/>";
}

if you wants to get category id which exits in $input_category then user this

$flipped = array_flip($categories);
foreach ( $input_categories as $v ) {

    echo $flipped[$v];      echo "<br/>";
}
Nipun Tyagi
  • 878
  • 9
  • 26
0

You can use array_keys() method for this. like below:

$ids = array_keys($categories);
echo "<pre>";
print_r($ids);
Amit Rajput
  • 2,061
  • 1
  • 9
  • 27