简体   繁体   中英

How to Reference/pull/sort by a specific key in a multidimensional array

I am writing a page that pulls images and image data out of a multidimensional array. I need to be able to click a button that calls a function to sort out the images by tags(IE tag_GlassDoor & tag_GlassWall) - basically to show only images that do or do not have that particular element (in this case im using 0 and 1 for yes and no), such as a glass door. I can currently make that array display the data, but I cant figure out how to sort the data by one of the array keys, or even really the syntax to pull a single value out at will.

   $arrImages[] = 
    [
        'img_sm'=>'image1.jpg', 
        'tag_GlassDoor'=>0,
        'tag_GlassWall'=>1,
    ];
   $arrImages[] = 
    [
        'img_sm'=>'image2.jpg', 
        'tag_GlassDoor'=>1,
        'tag_GlassWall'=>1,
    ];

Faltering is the answer, it can be used to filter one dimensional Arrays and multidimensional array. the general implementation would be something like this:

$arr = array(
    array(
        'image' => "data",
        'hasObject' => 1
    ),
    array(
        'image' => "data",
        'hasObject' => 0 
    ),
);
$finteredArray = array_filter($arr, function ($r) {
   return (bool) $r['hasObject'];
});

print_r($finteredArray);
// it outputs:
// Array ( [0] => Array ( [image] => data [hasObject] => 1 ) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM