我有這個陣列:
$config = [
'gallery_name' => 'My Gallery',
'unsplash_categories' => ['Nature' => '<img src = "https://source.unsplash.com/300x200/?nature" alt = "Nature" />',
'Water' => '<img src = "https://source.unsplash.com/300x200/?water" alt = "Water" />',
'Food' => '<img src = "https://source.unsplash.com/300x200/?food" alt = "Food" />',
'Night' => '<img src = "https://source.unsplash.com/300x200/?night" alt = "Night" />'],
'local_images' => ['1.jpg' => '<img src = "./images/1.jpg" alt = "Clem Onojeghuo" />', 'link1' => '<a href = "https://unsplash.com/@clemono"> Clem Onojeghuo </a>',
'2.jpg' => '<img src = "./images/2.jpg" alt = "Jordan Whitt" />', 'link2' => '<a href = "https://unsplash.com/@jwwhitt"> Jordan Whitt </a>',
'3.jpg' => '<img src = "./images/3.jpg" alt = "Michael Kucharski" />', 'link3' => '<a href = "https://unsplash.com/@intacts"> Michael Kucharski </a>',
'4.jpg' => '<img src = "./images/4.jpg" alt = "Paul Gilmore" />', 'link4' => '<a href = "https://unsplash.com/@pueblovista"> Paul Gilmore </a>' ]
我只想計算“本地影像”陣列中的第一個鍵。即:1.jpg、2.jpg、3.jpg、4.jpg,不是鏈接1、鏈接2、鏈接3、鏈接4。
我在用:
<h1><?php echo(count($config['local_images'])) . " Large Images" ?></h1>
但它輸出 8,因為我知道它們總共是這個陣列的 8 個鍵,但是我只想定位 '.jpg' 鍵。有沒有辦法做到這一點?
uj5u.com熱心網友回復:
您需要遍歷鍵,并且可以使用正則運算式匹配來檢查它們是否以.jpg.
<?php
function getJpgCount($config){
return count(array_filter(array_keys($config['local_images']),fn($key) => preg_match('/\.jpg$/i', $key)));
}
echo getJpgCount($config);
uj5u.com熱心網友回復:
您可以使用過濾器,然后對過濾后的陣列應用計數。
<?php
$config = [
'gallery_name' => 'My Gallery',
'unsplash_categories' => [
'Nature' => '<img src = "https://source.unsplash.com/300x200/?nature" alt = "Nature" />',
'Water' => '<img src = "https://source.unsplash.com/300x200/?water" alt = "Water" />',
'Food' => '<img src = "https://source.unsplash.com/300x200/?food" alt = "Food" />',
'Night' => '<img src = "https://source.unsplash.com/300x200/?night" alt = "Night" />'
],
'local_images' => [
'1.jpg' => '<img src = "./images/1.jpg" alt = "Clem Onojeghuo" />', 'link1' => '<a href = "https://unsplash.com/@clemono"> Clem Onojeghuo </a>',
'2.jpg' => '<img src = "./images/2.jpg" alt = "Jordan Whitt" />', 'link2' => '<a href = "https://unsplash.com/@jwwhitt"> Jordan Whitt </a>',
'3.jpg' => '<img src = "./images/3.jpg" alt = "Michael Kucharski" />', 'link3' => '<a href = "https://unsplash.com/@intacts"> Michael Kucharski </a>',
'4.jpg' => '<img src = "./images/4.jpg" alt = "Paul Gilmore" />', 'link4' => '<a href = "https://unsplash.com/@pueblovista"> Paul Gilmore </a>'
]
];
$filteredArray = array_filter($config['local_images'], function($k) {
if(strpos($k, 'jpg') !== false)
return $k;
}, ARRAY_FILTER_USE_KEY);
var_dump(count($filteredArray));
你可以在這里查看https://phpsandbox.io/n/white-sound-eken-zjnnp
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/405860.html
標籤:
下一篇:在FlutterWeb中使用httppost獲取用于RazorpayAPI呼叫的XMLHttpRequest錯誤
