按特定数组键的值对库进行排序,然后显示另一个键的值



我有一个多维数组,用于将图像和数据拉入页面。页面还将有一个排序系统,该系统将只显示具有特定标记的数组项目(当前用0和1标记是或否(。我正在使用if语句来决定页面是显示默认值(所有照片(还是显示排序的数组。默认值本身运行良好,但我正在尝试使排序显示。当我包括用于显示图像的html.php;echo$mImage['img_option']"(这是一个替身,我只是测试我是否能让语句显示项目。它显示的不是完整的标题字符串,而是每个键的每个值的第一个字符。(;出乎意料的";{或<",页面无法加载。我基本上必须在三天的时间里自学php,所以我肯定错过了一些简单的东西。我将包括一个数组的例子,排序的php,以及显示整个数组的部分。

这是我的阵列

$arrImages[] = 
[
'img_sm'=>'exampleple.jpg', 
'img_lg'=>'example2.thumb.jpg',
'img_caption'=>'multifamily',
'img_description'=>'example',
'img_path' => 'img/getest',
'img_type'=>'getest',
'MultiFamily'=>1,
];
$arrImages[] = 
[
'img_sm'=>'example.jpg', 
'img_lg'=>'example.thumb.jpg',
'img_caption'=>'notmultifamily',
'img_description'=>'example786',
'img_path' => 'img/getest',
'img_type'=>'getest',
'MultiFamily'=> 0,
];

这是if语句

<?php 
$sorted = 1;
//If the viewer is sorting, check what they are sorting by and then sort by that before pushing the page to change display. 
if ($sorted = 1){//start if sorted statement
$MultiFamilySorted = 1; //replace this with a function that checks all checkboxes to see if they are sorted by that or not. This is simulating that the viewer is sorting to see only multifamily homes.
foreach($arrImages as $sortedImages)://Start sort loop
if ($sortedImages['MultiFamily'] = 1){//start display sorted
foreach($sortedImages as $mImage): //start display loop
echo $mImage['img_caption'];//i am just using this to test if it will display 
endforeach;
}//end display sorted
endforeach;
}//end if sorted statement
?>

这是我默认显示的部分

<div class="ImageDisplayTestBox">
<?php 
foreach($arrImages as $mImage): //loop through the image array
?>
<div class="masonry-item no-default-style col-sm-3">
<a href="<?php echo $mImage['img_path'] . '/' . $mImage['img_lg']; ?>">
<span class="thumb-info thumb-info-centered-info thumb-info-no-borders">
<span class="thumb-info-wrapper">
<img src="<?php echo $mImage['img_path'] . '/' . $mImage['img_sm']; ?>" class="img-fluid" alt="">
<span class="thumb-info-title">
<span class="thumb-info-inner"><?php echo $mImage['img_caption']; ?></span>
<span class="thumb-info-type"><?php echo $mImage['img_type']; ?></span>
</span>
<span class="thumb-info-action">
<span class="thumb-info-action-icon"><i class="fas fa-plus"></i></span>
</span>
</span>
</span>
</a>
</div>
<?php endforeach; //end loop ?>
</div>

谢谢!

我没有检查您的代码中是否存在您提到的语法错误,但有一种更简单的方法:

<?php 
if ($sorted == 1){
$arrImages = array_filter($arrImages, function($image){
return $image['MultiFamily'] == 0;
});
}
?>

您可以使用它来代替排序代码。

这将为每个数组成员执行排序功能。如果函数返回true,它将把它传递给已排序的数组。如果它是假的,它将跳过它。

array_filter的文档如下:https://www.php.net/manual/de/function.array-filter.php

最新更新