I have an array with multiple array, and in each array one of the fields is another array, see below. I need to find the value for "First name", in the array that has an ‘item_id’ of value 177. How can I do that?
array(1) {
[0]=> array(4)
{
["product_id"]=> int(62)
["item_id"]=> int(177)
["quantity"]=> int(1)
["options"]=> array(5) {
[0]=> array(4) {
["field_id"]=> string(13) "655259ef26f01"
["label"]=> string(11) "First name:"
["value"]=> string(4) "test" ["type"]=> string(4) "text" }
[1]=> array(4) { ["field_id"]=> string(13) "65525a47553c3"
["label"]=> string(10) "Last name:"
["value"]=> string(4) "test" ["type"]=> string(4) "text" }
[2]=> array(4) {
["field_id"]=> string(13) "65525a658669b"
["label"]=> string(15) "E-mail address:"
["value"]=> string(17) "[email protected]"
["type"]=> string(5) "email" }
[3]=> array(4) { ["field_id"]=> string(13) "65525a964be34"
["label"]=> string(27) "Language for questionnaire:"
["value"]=> string(6) "German"
["type"]=> string(6) "select" }
} }
[1]=> array(4) {
["product_id"]=> int(62)
["item_id"]=> int(182)
["quantity"]=> int(1)
["options"]=> array(7) {
[0]=> array(4) {
["field_id"]=> string(13) "655259ef26f01"
["label"]=> string(11) "First name:"
["value"]=> string(4) "test"
["type"]=> string(4) "text"
}
[1]=> array(4) {
["field_id"]=> string(13) "65525a47553c3"
["label"]=> string(10) "Last name:"
["value"]=> string(4) "test"
["type"]=> string(4) "text"
}
[2]=> array(4) {
["field_id"]=> string(13) "65525a658669b"
["label"]=> string(15) "E-mail address:"
["value"]=> string(17) "[email protected]"
["type"]=> string(5) "email"
}
[3]=> array(4) {
["field_id"]=> string(13) "65525a7bb053f"
["label"]=> string(46) "Send copy of the report to this email address:"
["value"]=> string(17) "[email protected]"
["type"]=> string(5) "email"
}
[4]=> array(4) {
["field_id"]=> string(13) "65525a964be34"
["label"]=> string(27) "Language for questionnaire:"
["value"]=> string(7) "Chinese" ["type"]=> string(6) "select" }
} } }
I have tried several things, one of them this:
$fname = $customs['item_id'][$itemID]['options']['field_id']['655259ef26f01']['value'];
2
Answers
You can use a function that searches through the
$custom
array, then if theitem_id
matches what is passed, look through theoptions
sub-array and then pluck out thevalue
whenfield_id
matches:Yields:
If you just want one field, the using
foreach
makes sense. If you are going to fetch several field values it can help to convert your fields array into an indexed array with the field_id as the index. This can easily be done usingarray_column()
So something like
If you use this data on a regular basis, it may be useful to create the original data with some useful index (perhaps having product_id at the top level and field_id for the options) to help in fetching the values.