Search code examples
phparraysmultidimensional-arrayarray-filter

Return multiple values from PHP array


How could I filter through each array in this array to grab only certain pieces of data such as tid, uid and device?

I have used array_column to get only one piece of information but how could I get multiple ones?

$object = $ticket->find();
$arr = json_decode(json_encode($object), true);
var_dump($arr);

The snippet of code above is what returns the array of data.

array (size=2)
  0 => 
    array (size=9)
      'tid' => string '1' (length=1)
      'uid' => string '22' (length=2)
      'subject' => string 'iPhone 8' (length=8)
      'issue' => string 'iPhone 8 screen replacement' (length=27)
      'device' => string 'iPhone 8' (length=8)
      'created' => string '2017-05-25 00:01:11' (length=19)
      'identifier' => string '29cd54bf' (length=8)
      'status' => string 'New' (length=3)
      'tech' => string 'None' (length=4)
  1 => 
    array (size=9)
      'tid' => string '2' (length=1)
      'uid' => string '22' (length=2)
      'subject' => string 'iPhone 7' (length=8)
      'issue' => string 'iPhone 7 screen replacement' (length=27)
      'device' => string 'iPhone 7' (length=8)
      'created' => string '2017-05-25 00:27:42' (length=19)
      'identifier' => string 'b47f2c82' (length=8)
      'status' => string 'New' (length=3)
      'tech' => string 'None' (length=4)

Expected output:

array(2) {
    [0]=> array(3) {
        [0]=> string(1) "1"
        [1]=> string(2) "22"
        [2]=> string(8) "iPhone 8"
    }
    [1]=> array(3) {
        [0]=> string(1) "2"
        [1]=> string(2) "22"
        [2]=> string(8) "iPhone 7"
    }
}

Solution

  • Here we are using array_map to achieve desired output.

    Solution 1:

    Try this code snippet here

    $array=array_map(function($value){
        return array($value["tid"],$value["uid"],$value["subject"]);
    },$array);
    print_r($array);
    

    Solution 2:

    Try this code snippet here

    foreach($array as $value)
    {
        $result[]=array($value["tid"],$value["uid"],$value["subject"]);
    }
    print_r($result);