I have an array of objects of this form,
[{value => 1, name => "Ha"},
{value => 2, name => "Hi"},
{value => 3, name => "Ho"},
.....]
and a function that should return the value given a certain name,
the function is:
public function get_value_from_name($myArray, $name){
$arrays = $myArray;
foreach ($arrays as $arr){
if ($name == $arr->name){
return $arr->value;
}
}
return false;
}
}
when I use the function and pass it the array and a string this way get_value_from_name($myArray, "Hi") I expect getting a 2 but it returns false, I tried tracing the results, the foreach loops through the whole array but I think that $arr->name doesn't give anything, I am not sure. Can you check if something is wrong with my function, I am new to PHP.
Thanks in advance.
EDIT ********** UPDATE: That's what I get when debugging
public function get_value_from_name($arr, $names){ //$arr: {[2], [2], [2], [2] + 72 more} $names: "Hi"
$arrays = $arr; //{ $arrays: {[2], [2], [2], [2] + 72 more}
foreach ( $arrays as $array ){ // $arrays: {[2], [2], [2], [2] + 72 more} $array: {value => 79, name => "HiHiHiHiHiHi"}[2]
if ( $array->name == $names) //{$names: "Hi"
return $array->value;
}
}
return false;
}
My Solution : I managed to make it work this way, But can someone explain why the first function did not work,
public function get_id_from_name($arr, $names){
$arrays = $arr;
$nameArray = array_column($arrays, 'name');
$valueArray = array_column($arrays, 'value');
foreach (array_combine($valueArray, $nameArray) as $value=> $name) {
if ($name == $names) {
return $value;
}
}
return false;
}