I have an array in PHP with a structure similar to the following (obtained using el fech_all()
to get all the rows of a table):
var_dump() from $miarray
array(3) {
[0]=> array(3) {
[0]=> string(1) "1" // option_id
[1]=> string(9) "site_name" // option_name
[2]=> string(8) "FullAuth" // option_value
}
[1]=> array(3) {
[0]=> string(1) "2" // option_id
[1]=> string(8) "home_url" // option_name
[2]=> string(25) "http://ejemplo.com" // option_value
}
[2]=> array(3) {
[0]=> string(1) "3" // option_id
[1]=> string(8) "auth_url" // option_name
[2]=> string(31) "http://ejemplo.com/user/" // option_value
}
}
For better understanding, each of these subarrays is an option stored in a database and what I want to achieve is to access the value (option_value) of each of the options just by knowing its name (option_name).
I would like to get something like this:
function obtenerOpcion($option_name) {
// Buscar la opción dentro de $miarray
// return...
}
echo obtenerOpcion("home_url"); // http://ejemplo.com
If I understand correctly, given a value like
home_url
or another, you want to get the value that follows, in this case:http://ejemplo.com
Based on the array you have, you can program a function like this:
Let's test the function with several possibilities:
Recommendation
Since it
fetch_all
accepts a parameter to create associative arrays, you'd be better off creating an array of that type, so you can more accurately access the value using the column name.In the given answer it is assumed that there are no irregularities in the array (it will always
option_value
be afteroption_name
), otherwise the correct value would not be obtained, that is why it is always safer to obtain the values by the name of the index and not by the Sequential number.If
fetch_all
the flag for associative array were passed, it would be created like this:NOTE that I have intentionally put a different order on the second array.
There would be no problem, because the function will search for the value by the name of the key, regardless of whether it is after or before
option_name
:Also, this would make the code more portable . Let us suppose that we want to search not only for the
option_value
, but in some cases theoption_id
. The same function would do, adding a third parameter and an extra check on$mKey
:Various tests:
Starting from an array in PHP similar to the one proposed:
You create a function, which has to receive two arguments , one argument for the search and another argument that must be the array where the search should be performed. You can do something similar to the following:
The result
echo
will be the desired:You can also create a function that receives only the desired argument like this:
In a two-dimensional array, two indices are needed to select an element.
array_column
generate array ["site_name","home_url","auth_url] findarray_search
position of option_name in said array