John Davidson

php - How to find the first element with a specific value in multidimansional array?

0 comments
Message:


$userarray = array(
array(
'uid' => '100',
'extraid' => 2,
'name' => 'Sandra Shush',
'pic_square' => 'urlof100'
),
array(
'uid' => '5465',
'extraid' => 2,
'name' => 'Stefanie Mcmohn',
'pic_square' => 'urlof100'
),
array(
'uid' => '40489',
'extraid' => 2,
'name' => 'Michael',
'pic_square' => 'urlof40489'
),
array(
'uid' => '512',
'extraid' => 3,
'name' => 'Hillary',
'pic_square' => 'urlof409'
),
array(
'uid' => '792',
'extraid' => 3,
'name' => 'James',
'pic_square' => 'urlof489'
),
);

$all_category = $this->common->getAll(TABLE_CONF_CATEGORIES, 'year', $year);
foreach($all_category as $cats) {
$key = array_search($cats->id, array_column($userarray , 'extraid'));echo $key;
if($key) {
$userarray[$key]->category_name = $cats->category_name;
}
}

In this array, I need to get every first element of extraid. i.e. if extraid = 2, here's 3 elements are there, so I need to get the first array. If extraid = 3, then there's 2 arrays are there, & I need the first array to fetched, & so on.


this all_category is another array where the corresponding extraid values are present, so looped it, & did an array search to find the value.



My Answer:
Here is the updated code to find the first element with a specific value in the multidimensional array:

php
$userarray = array(
array(
'uid' => '100',
'extraid' => 2,
'name' => 'Sandra Shush',
'pic_square' => 'urlof100'
),
array(
'uid' => '5465',
'extraid' => 2,
'name' => 'Stefanie Mcmohn',
'pic_square' => 'urlof100'
),
array(
'uid' => '40489',
'extraid' => 2,
'name' => 'Michael',
'pic_square' => 'urlof40489'
),
array(
'uid' => '512',
'extraid' => 3,
'name' => 'Hillary',
'pic_square' => 'urlof409'
),
array(
'uid' => '792',
'extraid' => 3,
'name' => 'James',
'pic_square' => 'urlof489'
),
);

$all_category = $this->common->getAll(TABLE_CONF_CATEGORIES, 'year', $year);
foreach($all_category as $cats) {
foreach($userarray as $key => $user) {
if($user['extraid'] == $cats->id) {
$userarray[$key]['category_name'] = $cats->category_name;
break; // Stop the loop after finding the first element with the specific value
}
}
}


This code will loop through the `$all_category` array and then loop through the `$userarray` to find the first element with the specific `extraid` value. Once found, it will add the `category_name` from the `$all_category` array to the corresponding element in the `$userarray`. The `break` statement is used to stop the loop after finding the first element with the specific value.

Rate this post

3 of 5 based on 6203 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us