Tanvir Alam Tanvir Alam - 6 months ago 8
SQL Question

php iterate an associative array

I have the following array:

array(5) {
[83]=>
object(stdClass)#39 (17) {
["id"]=>
int(83)
["product_id"]=>
int(15)
["area_id"]=>
int(2)
["termtype_id"]=>
int(40)
["name"]=>
string(23) "XXXXXX"
}
[89]=>
object(stdClass)#398 (17) {
["id"]=>
int(89)
["product_id"]=>
int(15)
["area_id"]=>
int(2)
["termtype_id"]=>
int(40)
["name"]=>
string(23) "YYYYY"
}
[102]=>
object(stdClass)#394 (17) {
["id"]=>
int(102)
["product_id"]=>
int(23)
["area_id"]=>
int(2)
["termtype_id"]=>
int(40)
["name"]=>
string(23) "ZZZZZ"
}
[104]=>
object(stdClass)#397 (17) {
["id"]=>
int(104)
["product_id"]=>
int(23)
["area_id"]=>
int(2)
["termtype_id"]=>
int(40)
["name"]=>
string(23) "AAAAA"
}
[107]=>
object(stdClass)#399 (17) {
["id"]=>
int(107)
["product_id"]=>
int(23)
["area_id"]=>
int(2)
["termtype_id"]=>
int(40)
["name"]=>
string(23) "KKKK"
}
}


The above array is generated from a sql query and iterated using the following function:

public function keyArray($arr) {
$result = [];
foreach($arr as $element) {
$result[$element->id] = $element;
}
return $result;
}


Is there anyway I can iterate the above ARRAY and get all data related to product_id?

following would be a result:

array(2){
[83]=>
object(stdClass)#39 (17) {
["id"]=>
int(83)
["product_id"]=>
int(15)
["area_id"]=>
int(2)
["termtype_id"]=>
int(40)
["name"]=>
string(23) "XXXXXX"
}
[89]=>
object(stdClass)#398 (17) {
["id"]=>
int(89)
["product_id"]=>
int(15)
["area_id"]=>
int(2)
["termtype_id"]=>
int(40)
["name"]=>
string(23) "YYYYY"
}
}


Any help would be appreciated?

Answer

Convert your function like this, $searchProductId is the product_id for search all data related to product_id:

    public function keyArray($arr, $searchProductId) {
        $result = [];
        foreach($arr as $element) {
            if($element->product_id == $searchProductId){
                $result[$element->id] = $element;
            }
        }
        return $result;
    }