0

I am using user user input into a form and then it will be searching through this array to see if their input is inside the array. So If a user searches for '45' I need to find its corresponding values in the array.

So if $myArray['Aames'][o] is 45 i need to also find $myArray['Names'][0] and so on. So i need a way to find the element number of '45' and store that number then print out the corresponding information.

 $myArray = array
                ( 
                "Names"=>array
                (
                "John",
                "Jane",
                "Rick"
                ),
                "Speciality"=>array
                (
                "Buisness",
                "sales",
                "marketing"
                ),
                "Aames"=>array
                (
                 "45",
                "Some guy",
                "Another guy"
                )
                );
2
  • And when they search for "John", you also want to return "Business", "45" ? Commented Jun 14, 2011 at 19:21
  • Loop through $myArray, checking in_array for each $element and do something when it's found. What code have you written? Commented Jun 14, 2011 at 19:22

2 Answers 2

1
$search = '45';

$key = array_search($search, $myArray['Aames']);

$name = $myArray['Names'][$key];

$speciality = $myArray['Speciality'][$key];

echo $name; //Outputs John

echo $speciality; //Outputs Business
0

You could generalize this a a bit with a function if you plan to apply it more generally.

function searchArray($query, $keyArray, $valuesArray){

    $key = array_search($query, $keyArray);

    $returnArray = array();
    foreach($valuesArray as $arrKey=>$arrVal){
        $returnArray[$arrKey] = $arrVal[$key];
    }

    return $returnArray;
}

$query is a string containing the value you are looking for in $keyArray and $valuesArray is an array of arrays that contain the values associated with the potential query strings.

Example: $userAttributes = searchArray('45', $myArray['Aames'], array('Names'=>$myArray['Names'], 'Speciality'=>$myArray['Speciality']));

$userAttributes should then be array('Names'=>'John', 'Speciality'=>'Buisness') [sic]

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.