2

I'm trying to search for a substring within part of the bottom layer of a 2-layer array and return the key from the top layer. E.g. in the array below searching within "A" for "ca" would return "0" and "2" (but would miss "cattle"):

Array (
    [0] => Array (
        [A] => cat
        [B] => horses
        )
    [1] => Array (
        [A] => dog
        [B] => cattle
    )
    [2] => Array (
        [A] => cat
        [B] => sheep
    )
) 
3
  • Two ways: first, loop throw all elements in the layer 1 array then test values in layer 2 element, or transform the array into a only one dimensional array. Commented Sep 19, 2012 at 19:52
  • @Eric - My current method works (for a very limited number of applications) but is inflexible and over-elaborate. I won't bore you with the full details but it involves generating an array of possible strings (it uses in_array so won't work for substrings) and searching for those. I don't want to have to generate this further array. Commented Sep 19, 2012 at 20:10
  • @FIG-GHD742 - Thanks but could you give an example of the first approach? I've been using foreach loops and in_array but it's searching for a substring that I can't get working Commented Sep 19, 2012 at 20:12

1 Answer 1

2

You can try like this :

$array = array(
    array(
        "A" => "cat",
        "B" => "horse"
    ),
    array(
        "A" => "dog",
        "B" => "cattle"
    ),
    array(
        "A" => "cat",
        "B" => "sheep"
    ),
);

$result = mySearch($array, "A", "ca");

function mySearch($array, $key, $search)
{
    $results = array();
    foreach ($array as $rootKey => $data) {
        if (array_key_exists($key, $data)) {
            if (strncmp($search, substr($data[$key], 0, 2), strlen($search)) == 0) {
                $results[] = $rootKey;
            }
        }
    }
    return $results;
}

var_dump($result);

Will output :

array(2) {
  [0]=>
  int(0)
  [1]=>
  int(2)
}

Note that this method is not encoding safe (you may use mb_str* instead of str* function family, more details here).

Sign up to request clarification or add additional context in comments.

1 Comment

@user1684046 This is a good way how my first approach will loop, as you can see, wee use a foreach loop for loop throw all item in the first dimensional array. Then test each childen for select data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.