php array manipulation in multidimensional arrays. getting data in array form with all have the same keys [closed]

StackOverflow https://stackoverflow.com/questions/23525579

Question

I have a result of arrays that has contain like this:

array(
   [0]=>array(
       ["id"]=>56,
       ["name"]=>"john",
       ["company_id"]=>1,
       ["profession"]=>"IT";
   )
   [1]=>array(
       ["id"]=>57,
       ["name"]=>"jane",
       ["company_id"]=>2,
       ["profession"]=>"QC Assistant";
   )
   [2]=>array(
       ["id"]=>58,
       ["name"]=>"Bert",
       ["company_id"]=>1,
       ["profession"]=>"IT Specialist";
   )
   [3]=>array(
       ["id"]=>60,
       ["name"]=>"Roy",
       ["company_id"]=>3,
       ["profession"]=>"Plumber";
   )
)

now my problem is I need to search all company_id = 1 and put it in array form with all his keys and values inside.

Was it helpful?

Solution

$new_arr = array();

foreach ($arr as $a)
    if ($a['company_id']==1)
        $new_arr[] = $a;

print_r($new_arr);

Result:

Array
(
    [0] => Array
        (
            [id] => 56
            [name] => john
            [company_id] => 1
            [profession] => IT
        )

    [1] => Array
        (
            [id] => 58
            [name] => Bert
            [company_id] => 1
            [profession] => IT Specialist
        )

)

OR, if you don't want company_id included in the new array, where company_id is always 1, then

$new_arr = array();
foreach ($arr as $a)
    if ($a['company_id']==1) {
        unset($a['company_id']);
        $new_arr[] = $a;
    }

print_r($new_array);

Result:

Array
(
    [0] => Array
        (
            [id] => 56
            [name] => john
            [profession] => IT
        )

    [1] => Array
        (
            [id] => 58
            [name] => Bert
            [profession] => IT Specialist
        )

)

OTHER TIPS

You can also do it using array_filter():

$a = array_filter($a, function($v){return $v['company_id']==1;});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top