-1

I'm trying to get the data in the array according to the input value, like the example below, if I enter the correct value, it will get the value, but when I enter the incorrect value, it doesn't work.

You can see a small example below.

<?php
   echo "<pre>";
   $array = [
        [
            "id" => "33704",
            "name" => "Total apple"
        ],
        [
            "id" => "33706",
            "name" => "Used apple"
        ],
        [
            "id" => "33694",
            "name" => "banana: Bits received"
        ],
        [
            "id" => "33697",
            "name" => "banana: Bits sent"
        ]
    ];
    
print_r($array);
function searchItem($array, $key, $value)
{
    $results = array();
    if (is_array($array)) {
        if (isset($array[$key]) && $array[$key] == $value) {
            $results[] = $array;
        }
        foreach ($array as $subarray) {
            $results = array_merge($results, searchItem($subarray, $key, $value));
        }
    }
    return $results;
}

$result = searchItem($array, 'name', 'Bits received');
print_r($result);

When I enter the exact value 'banana: Bits received' it can be retrieved, but the value is many and unlimited, I want when I enter 'Bits received' it must also be found. Hope everyone can help. Thanks!

2 Answers2

1

you can use strstr or strpos or even preg_match to achieve this.

foreach ($array as $sub) {
    if (strstr($sub['name'], $value) !== false) {
        // founded value
    }
}

however, this may be a more complicated task, you may need to include more advanced techs with this, like databases & Fulltext search, or some indexing softwares like elastic search and so on.

hassan
  • 7,812
  • 2
  • 25
  • 36
1

There are built-in functions for this: array_filter and str_contains:

$result = array_filter(
    $array,
    function ($item) {
      return str_contains($item['name'], 'Bits received');
    }
);

The same solution with an arrow function:

$result = array_filter(
    $array,
    fn($item) => str_contains($item['name'], 'Bits received')
);

Moving array_filter into a function:

function searchItem($array, $key, $value) {
  return array_filter(
      $array,
      fn($item) => str_contains($item[$key], $value)
  );
}

$result = searchItem($array, 'name', 'Bits received');
print_r($result);
lukas.j
  • 6,453
  • 2
  • 5
  • 24