我有:
$hotels
的变量,用于获取已注册酒店的字段; 对于$hotels
,我使用的get_field
属性与array
类似。在这个数组中,我必须得到帖子的名称(这是酒店的名称)。我想搜索array
酒店名称并将其打印在页面中。
如果我编码:
<?php
$hotels = get_field('produtos_hotel');
print_r($hotels);
$key = array_search('Ocean Maya Royale', $hotels);
echo $key; // should display 'Ocean Maya Royale';
?>
它会输出这个烂摊子:
Array (
[0] => WP_Post Object (
[ID] => 1113
[post_author] => 1
[post_date] => 2014-06-11 16:18:59
[post_date_gmt] => 2014-06-11 19:18:59
[post_content] =>
[post_title] => Ocean Maya Royale
[post_excerpt] =>
[post_status] => publish
[comment_status] => open
[ping_status] => open
[post_password] =>
[post_name] => ocean-maya-royale
[to_ping] =>
[pinged] =>
[post_modified] => 2014-06-18 14:41:25
[post_modified_gmt] => 2014-06-18 17:41:25
[post_content_filtered] =>
[post_parent] => 0
[guid] => http://localhost/mydocs/advtour/newsite/wordpress/?post_type=add_content&p=1113
[menu_order] => 0
[post_type] => add_content
[post_mime_type] =>
[comment_count] => 0
[filter] => raw
)
[1] => WP_Post Object (
[ID] => 1302
[post_author] => 1
[post_date] => 2014-06-12 01:19:36
[post_date_gmt] => 2014-06-12 04:19:36
[post_content] =>
[post_title] => Flamingo Cancun Resort
[post_excerpt] =>
[post_status] => publish
[comment_status] => open
[ping_status] => open
[post_password] =>
[post_name] => flamingo-cancun-resort
[to_ping] =>
[pinged] =>
[post_modified] => 2014-06-18 14:40:19
[post_modified_gmt] => 2014-06-18 17:40:19
[post_content_filtered] =>
[post_parent] => 0
[guid] => http://localhost/mydocs/advtour/newsite/wordpress/?post_type=add_content&p=1302
[menu_order] => 0
[post_type] => add_content
[post_mime_type] =>
[comment_count] => 0
[filter] => raw
)
)
你们能看到[post_title]
元素吗?所以,我必须采用Ocean Maya Royale
或Flamingo Cancun Resort
,但array_search
无法找到它!
谢谢!
答案 0 :(得分:1)
$srch = 'Ocean Maya Royale';
foreach ($hotels as $key => $val) {
$key1 = array_search($srch, $hotels[$key]);
echo $key . ' ' . $key1 . chr(10) . '<br />';
}
它是一个二级数组,因此需要通过迭代进行迭代。如果要在&lt; post_title&#39;的特定第二个下标中找到搜索字符串。它可以是硬编码的,单独的第一个下标可以像。
一样返回$srch = 'Ocean Maya Royale';
foreach ($hotels as $key => $val) {
if ($srch == $hotels[$key]['post_title'])
echo $key . chr(10) . '<br />';
}
答案 1 :(得分:0)
array_search
为您提供数组的键,而不是变量。所以要获得标题使用这个变量:
$theTitle = $hotels[$key]->post_title;
echo $theTitle;
所以array_search在查找该标题时会返回0
的密钥,因为该元素中包含该标题。
<强> // // EDIT 强>
因为您有一个对象数组,所以需要更改array_search以考虑对象:
array_search(array('post_title' => 'Ocean Maya Royale')
答案 2 :(得分:0)
使用array_reduce过滤的基本形式:
array_reduce( $hotels, function($result, $item) {
if ($item->post_title == 'Ocean Maya Royale') {
$result[] = $item;
}
}, array());
您还可以将其转换为可重用性的功能:
function searchPostTitle($posts, $search_title)
{
array_reduce( $posts, function($result, $item) use ($search_title) {
if ($item->post_title == $search_title) {
$result[] = $item;
}
}, array());
}