-1

I need to search value in array and get its index but as per my code its giving wrong result. I am explaining my code below.

    $arr = [{
         "attribute_code":"cake_flavour",
         "value":"192"
     },
     {
       "attribute_code":"cake_weight",
       "value":"232"
    }]

  $p ='Cake flavour';


$atcodeindex = array_search(preg_replace('/[^a-z]/', "", strtolower($p)), preg_replace('/[^a-z]/', "", strtolower(array_column($arr, 'attribute_code'))));

echo $atcodeindex;

Here I am not getting the index at all. I need to check if value of $p is matching with that array if present the index should be fetched. here the expected output should be 0.

subhraedqart
  • 115
  • 6
  • Does this answer your question? [PHP - find entry by object property from an array of objects](https://stackoverflow.com/questions/4742903/php-find-entry-by-object-property-from-an-array-of-objects) – Ali May 23 '20 at 14:41
  • That is something different. – subhraedqart May 23 '20 at 14:47

1 Answers1

0

I think your problem is more trying to convert Cake flavour to cake_flavour. When that is done, all you have to do is search that in your array:

$arr = [[
  "attribute_code" => "cake_flavour",
  "value" => "192"
  ],
  [
    "attribute_code" => "cake_weight",
    "value" => "232"
]];

$p = str_replace(' ', '_', strtolower('Cake flavour'));
echo $p;
// -> 'cake_flavour'

for ($i = 0; $i < count($arr); $i++) {
  if ($arr[$i]['attribute_code'] === $p) {
    echo $i; // -> 0 
    break;
  }
};
gogaz
  • 2,323
  • 2
  • 23
  • 31