Tokotome
Tokotome

Reputation: 91

Get specific key value pairs from associative array

I`m new to PHP and probably this one is basic question, but...I have an associative array (result of json_decode function). For example it looks like this:

$cars = array
  (
  array("brand"=>"Volvo", "price" => 10000, "type"=> 1),
  array("brand"=>"Audi", "price" => 20000, "type"=> 2),
  array("brand"=>"Ford", "price" => 30000, "type"=> 3),
  array("brand"=>"Audi", "price" => 31000, "type"=> 3),
  array("brand"=>"Ford", "price" => 32000, "type"=> 2),
  array("brand"=>"Audi", "price" => 33000, "type"=> 2)
  );

I need to loop $cars and get just brand and price as key value pair where brand is Audi because of a need to convert each to an object then.

Thanks!

Upvotes: 1

Views: 1009

Answers (1)

alistaircol
alistaircol

Reputation: 1453

Pretty simple. Use foreach to iterate through each car. If car brand name is 'Audi' then it will add it the entry it's on to an array.

<?php
$cars = array
  (
  array("brand"=>"Volvo", "price" => 10000, "type"=> 1),
  array("brand"=>"Audi", "price" => 20000, "type"=> 2),
  array("brand"=>"Ford", "price" => 30000, "type"=> 3),
  array("brand"=>"Audi", "price" => 31000, "type"=> 3),
  array("brand"=>"Ford", "price" => 32000, "type"=> 2),
  array("brand"=>"Audi", "price" => 33000, "type"=> 2)
  );

$audis = [];  
foreach ($cars as $car) {
  if ($car['brand'] == 'Audi') {
    $audis[] = ['price' => $car['price'], 'type' => $car['type']];
  }
}

foreach ($audis as $audi) {
  print_r($audi);
}

This returns all Audi's

Array
(
    [price] => 20000
    [type] => 2
)
Array
(
    [price] => 31000
    [type] => 3
)
Array
(
    [price] => 33000
    [type] => 2
)

Link: https://eval.in/769607

Upvotes: 1

Related Questions