0

In an array like that :

    Array
    (
        [1] => Array
            (
                [name] => boat
                [id] => 2
            )

        [2] => Array
            (
                [name] => house
                [id] => 5
            )
    )

In php, How can i select the element "name" where the "id" is equal to 5 ? (house)

(Using the id 5 to have "house")

EDIT : can i avoid looping ? Something less power consuming maybe ?

bob dylan
  • 989
  • 2
  • 10
  • 26
  • 3
    Basic looping: `foreach ($array as $sub) { if ($sub['id'] == 5) { echo $sub['name']; } }` – Amal Murali May 12 '14 at 19:35
  • Perhaps you want to consider using [LINQ](https://plinq.codeplex.com/) or similar if you want to access arrays through a syntax similar to SQL; alternatively, a very simple [array_filter()](http://www.php.net/manual/en/function.array-filter.php)... but you can't avoid looping, simply hide the loop or loop through PHP's underlying C code – Mark Baker May 12 '14 at 19:35
  • You could also re-format your array for easier/faster access. Set the `id` as the first level key when building the array (or loop over afterwards and make a new array). – Jonathan Kuhn May 12 '14 at 19:41
  • Without doing something crazy, probably not. If you could show the code which creates this array then maybe it would be easier to get SQL to do the work for you =) – MonkeyZeus May 12 '14 at 19:45
  • You shouldn't ever be concerned about micro-performance early on imho. Bottlenecks lie often in other parts of a system. As already mentioned by @MonkeyZeus optimizing the query to return only one result and thus avoiding the loop entirely would be better in the long run. – nietonfir May 12 '14 at 20:23
  • @nietonfir Thank you for the suggestion but if we assume Bob wants to iterate the array and create some sort grouped-accordion thing the it would be inefficient to send a query every time the `name` changes especially if new names can be added on-the-fly. I was thinking something along the lines of `$sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP);` from **http://www.php.net/manual/en/pdostatement.fetchall.php** but I have never used it so I might just have to give this a shot with some things which I am doing =) – MonkeyZeus May 12 '14 at 20:39
  • Hey check this out: http://stackoverflow.com/questions/5361716/is-there-a-way-to-fetch-associative-array-grouped-by-the-values-of-a-specified-c/22063422#22063422 and good luck! – MonkeyZeus May 12 '14 at 20:42

4 Answers4

1

you must having loop directly or indirectly(in a built in method).And for your concern this loop will use less power.

try like this:

foreach($your_array as $a){

      if(in_array(5,$a)){ //check if 5 in this sub array
         print_r($a);
      }
    }

live demo

if you wanted to check multiple ids then you can do it like this way:

 $ids= array(1,3,5); //make an array of ids you want to filter

    foreach($array as $a){

      if(in_array($a["id"],$ids)){
         print_r($a);
      }
    }

demo2

Awlad Liton
  • 9,366
  • 2
  • 27
  • 53
1

Without a loop, you can do this:

$result = array_filter($your_array, function($arg) {
    return $arg['id'] == 5;
});

This will return an array with only the portion of the master array that matches. If you need to use a variable, then do it like this:

$var = 5;
$result = array_filter($your_array, function($arg) use $var {
    return $arg['id'] == $var;
});
mister martin
  • 6,197
  • 4
  • 30
  • 63
0

Here's another one for fun:

echo array_column($array, 'name', 'id')[5];
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
0

If your data isn't fitting in your schema very well, consider switching to something like MongoDB. From their docs:

Project Array Documents

A students collection contains the following documents where the grades field is an array of documents; each document contain the three field names grade, mean, and std:

{ "_id" : 7, semester: 3, "grades" : [ { grade: 80, mean: 75, std: 8 },
                                       { grade: 85, mean: 90, std: 5 },
                                       { grade: 90, mean: 85, std: 3 } ] }

{ "_id" : 8, semester: 3, "grades" : [ { grade: 92, mean: 88, std: 8 },
                                       { grade: 78, mean: 90, std: 5 },
                                       { grade: 88, mean: 85, std: 3 } ] }

In the following query, the projection { "grades.$": 1 } returns only the first element with the mean greater than 70 for the grades field:

db.students.find(
   { "grades.mean": { $gt: 70 } },
   { "grades.$": 1 }
)

The operation returns the following documents:

{ "_id" : 7, "grades" : [  {  "grade" : 80,  "mean" : 75,  "std" : 8 } ] }
{ "_id" : 8, "grades" : [  {  "grade" : 92,  "mean" : 88,  "std" : 8 } ] }

Written in PHP, this query would look like:

$mongoClient = new MongoClient("mongodb://localhost");
$students = $mongoClient->selectCollection("db", "students");
$query = array("grades.mean" => array('$gt' => 70));
$fields = array("grades.$" => 1);

$result = $students->find($query, $fields);
foreach($result as $grades) {
   print_r($grades);
}
QuickDanger
  • 1,032
  • 11
  • 18