Поиск строки PHP в многомерном массиве

Я только начал разбираться с PHP (новым для PHP) кодированием, связанным с Pinterest. Я застрял при выполнении поиска строки по многомерным массивам. Я провел много исследований и пробовал разные вещи, но не смог найти большой помощи в поиске строк по многомерным массивам.

В частности, Я пробовал рекурсивный поиск по массиву из этого поста: in_array () и многомерный массив но это не сработало для меня. Возможно, я делаю что-то не так, поэтому я здесь, чтобы найти помощь экспертов PHP.

Когда я запускаю его против моего многомерного массива (упомянуто ниже) Я получаю ответ каждый раз, и неважно, какую строку я укажу.

Например: если я запускаю приведенный ниже код, и он говорит, что нашел, хотя он должен сказать, что не найден, потому что есть Irix слово в моем многомерном массиве.

echo in_array_r("Irix", $info) ? 'found' : 'not found';

Ниже мой многомерный массив:

$info = array
(
"origin_pinner" => null,
"domain" => "teacherspayteachers.com",
"done_by_me" => null,
"videos" => null,
"tracking_params" => "CwABAAAADDk0NzI0ODYzODc2OAA",
"aggregated_pin_data" => array
(
"comment_count" => 0,
"did_it_data" => array
(
"recommend_scores" => array
(
"0" => array
(
"count" => 0,
"score" => 1,
),
"1" => array
(
"count" => 0,
"score" => 0.5,
),
"2" => array
(
"count" => 0,
"score" => 0,
),
),
"rating" => -1,
"user_count" => 1,
"tags" => array
(
),
"images_count" => 1,
"recommended_count" => 1,
"details_count" => 1,
"type" => "aggregateddiditdata",
),
"id" => 4894650307138568743,
"is_shop_the_look" => null,
"aggregated_stats" => array
(
"saves" => 13580,
"done" => 1,
),
),
"hashtags" => array
(
),
"like_count" => 0,
"images" => array
(
"736x" => array
(
"url" => "https://i.pinimg.com/736x/6c/a8/8e/6ca88ebc09648b14a88b125144993ef3.jpg",
"width" => 736,
"height" => 1380,
),
"60x60" => array
(
"url" => "https://i.pinimg.com/60x60/6c/a8/8e/6ca88ebc09648b14a88b125144993ef3.jpg",
"width" => 60,
"height" => 60,
),
"474x" => array
(
"url" => "https://i.pinimg.com/474x/6c/a8/8e/6ca88ebc09648b14a88b125144993ef3.jpg",
"width" => 474,
"height" => 888,
),
"170x" => array
(
"url" => "https://i.pinimg.com/170x/6c/a8/8e/6ca88ebc09648b14a88b125144993ef3.jpg",
"width" => 170,
"height" => 318,
),
"600x315" => array
(
"url" => "https://s-media-cache-ak0.pinimg.com/600x315/6c/a8/8e/6ca88ebc09648b14a88b125144993ef3.jpg",
"width" => 600,
"height" => 315,
),
"564x" => array
(
"url" => "https://i.pinimg.com/564x/6c/a8/8e/6ca88ebc09648b14a88b125144993ef3.jpg",
"width" => 564,
"height" => 1057,
),
"236x" => array
(
"url" => "https://i.pinimg.com/236x/6c/a8/8e/6ca88ebc09648b14a88b125144993ef3.jpg",
"width" => 236,
"height" => 442,
),
"136x136" => array
(
"url" => "https://i.pinimg.com/136x136/6c/a8/8e/6ca88ebc09648b14a88b125144993ef3.jpg",
"width" => 136,
"height" => 136,
),
"orig" => array
(
"url" => "https://s-media-cache-ak0.pinimg.com/originals/6c/a8/8e/6ca88ebc09648b14a88b125144993ef3.png",
"width" => 768,
"height" => 1440,
),
),
"id" => "AdJy70aUUiIeIp2s5VM5ulcoVr6xDsV_ff3K0oJCVQr-MoRBPMbAVRE",
"closeup_user_note" => "FREE Teaching Resource   Editable Novel Brochure on Google Classroom that students can edit for any novel!",
"category" => "education",
"price_currency" => "USD",
"is_promoted" => null,
"description_html" => "FREE Teaching Resource   Editable Novel Brochure on Google Classroom that students can edit for any novel!",
"per_pin_analytics" => array
(
"id" => "<Pin 448671181617679376>",
),
"section" => null,
"buyable_product" => null,
"access" => array
(
),
"is_promotable" => null,
"comment_count" => 1,
"board" => array
(
"category" => null,
"is_collaborative" => null,
"layout" => "default",
"description" => null,
"privacy" => "public",
"url" => "/rhythmsandtwine/novel-studies/",
"image_cover_url" => "https://s-media-cache-ak0.pinimg.com/200x150/17/3a/ab/173aab4ddb8d48f4d50002c1f95f6d22.jpg",
"pin_thumbnail_urls" => array
(
"0" => "https://s-media-cache-ak0.pinimg.com/150x150/d8/a3/34/d8a334af515fab7e5f73a15e5244f8ac.jpg",
"1" => "https://s-media-cache-ak0.pinimg.com/150x150/3f/4c/50/3f4c50eded7a107b4a49dea3c58a7848.jpg",
"2" => "https://s-media-cache-ak0.pinimg.com/150x150/04/67/ee/0467eead4aba47f47bb910a48cd1afdd.jpg",
"3" => "https://s-media-cache-ak0.pinimg.com/150x150/8f/90/af/8f90afe949fa0ef24d6a5a9bc85d2537.jpg",
"4" => "https://s-media-cache-ak0.pinimg.com/150x150/bf/ff/a5/bfffa5392c1f7c2317cd3e1cf2aa9920.jpg",
),
"image_thumbnail_url" => "https://s-media-cache-ak0.pinimg.com/upload/448671250316290197_board_thumbnail_2017-12-27-08-38-39_92111_60.jpg",
"access" => array
(
),
"collaborated_by_me" => null,
"owner" => array
(
"id" => 448671319035224306,
),
"map_id" => "pinterest.ijz1714i",
"followed_by_me" => null,
"type" => "board",
"id" => "448671250316290197",
"name" => "Novel Studies",
),
"link_domain" => array
(
"official_user" => null,
),
"type" => "pin",
"method" => "uploaded",
"image_signature" => "6ca88ebc09648b14a88b125144993ef3",
"attribution" => null,
"description" => "FREE Teaching Resource   Editable Novel Brochure on Google Classroom that students can edit for any novel!",
"price_value" => 0,
"liked_by_me" => null,
"show_personalize_field" => null,
"title" => null,
"native_creator" => null,
"is_playable" => null,
"rich_metadata" => array
(
"site_name" => "Teachers Pay Teachers",
"description" => "Novel Brochure - Pamphlet for Google Classroom Freebie! This resource allows students to create a pamphlet that can be edited for ANY novel! The file contains a Google Drive link that can be used for Google Classroom. **Be sure to MAKE A COPY of the link and save to your",
"link_status" => 0,
"title" => "Novel Brochure Google Classroom Freebie",
"locale" => "en",
"has_price_drop" => null,
"amp_url" => null,
"id" => "301b4d97d46163d2c9e3b22de2f0a345",
"url" => "https://www.teacherspayteachers.com/Product/Novel-Brochure-Google-Classroom-Freebie-3104649",
"tracker" => null,
"apple_touch_icon_link" => "https://s-media-cache-ak0.pinimg.com/favicons/e102b188545e64e45a326583a64a6bc332be2df9228a3f99685af702.png?155fe47b3e0bb98f4d90a12033216561",
"favicon_images" => array
(
"50x" => "https://s-media-cache-ak0.pinimg.com/favicons/50x/b95b678fa3287d329190f918cefbbac4a5a3e65a0212bc32f9e2c363.png?3eb3040f733c42a12569d94d396a07a4",
"orig" => "https://s-media-cache-ak0.pinimg.com/favicons/b95b678fa3287d329190f918cefbbac4a5a3e65a0212bc32f9e2c363.ico?3eb3040f733c42a12569d94d396a07a4",
),
"type" => "richpindataview",
"amp_valid" => null,
"apple_touch_icon_images" => array
(
"50x" => "https://s-media-cache-ak0.pinimg.com/favicons/50x/318e68afb755008848f5ec59beac068e50c4696d4f11e51552cd2271.png?d99a7f242e13fff1cd16b9b5de22ec0b",
"orig" => "https://s-media-cache-ak0.pinimg.com/favicons/318e68afb755008848f5ec59beac068e50c4696d4f11e51552cd2271.png?d99a7f242e13fff1cd16b9b5de22ec0b",
),
"favicon_link" => "https://s-media-cache-ak0.pinimg.com/favicons/09f765214b80be5f5198899864e6996540ed8a4e54fee82ce58fd606.ico?fbf2fa4d283a37a435dde24f48537e7d",
),
"via_pinner" => array
(
"username" => "dezi4462",
"first_name" => "Dezi",
"domain_url" => null,
"twitter_url" => null,
"domain_verified" => null,
"image_medium_url" => "https://i.pinimg.com/75x75_RS/f2/61/06/f261063238cc0672f1eb586352660452.jpg",
"explicitly_followed_by_me" => null,
"is_default_image" => null,
"location" => null,
"full_name" => "Dezi Martinez",
"indexed" => null,
"verified_identity" => array
(
),
"image_small_url" => "https://i.pinimg.com/30x30_RS/f2/61/06/f261063238cc0672f1eb586352660452.jpg",
"followed_by_me" => null,
"type" => "user",
"id" => "375417456346283592",
),
"link" => "https://www.teacherspayteachers.com/Product/Novel-Brochure-Google-Classroom-Freebie-3104649",
"has_required_attribution_provider" => null,
"is_repin" => 1,
"rich_recipe_top_ingredients" => array
(
),
"buyable_product_availability" => null,
"pinner" => array
(
"username" => "rhythmsandtwine",
"first_name" => "Jennifer",
"domain_url" => null,
"twitter_url" => null,
"domain_verified" => null,
"image_medium_url" => "https://i.pinimg.com/75x75_RS/ae/c0/ac/aec0acd834181d845ee39e437dbd939c.jpg",
"explicitly_followed_by_me" => null,
"is_default_image" => null,
"location" => null,
"full_name" => "Jennifer Forbes",
"indexed" => null,
"verified_identity" => array
(
),
"image_small_url" => "https://i.pinimg.com/30x30_RS/ae/c0/ac/aec0acd834181d845ee39e437dbd939c.jpg",
"followed_by_me" => null,
"type" => "user",
"id" => 448671319035224306,
),
"repin_count" => 354,
"tracked_link" => "https://www.teacherspayteachers.com/Product/Novel-Brochure-Google-Classroom-Freebie-3104649",
"created_at" => "Fri, 09 Jun 2017 23:54:29 +0000",
"is_native" => null,
"native_pin_stats" => null,
"promoter" => null,
"pin360" => null,
"privacy" => "public",
"dominant_color" => "#859886",
"promoted_is_removable" => null,
"embed" => null,
"is_quick_promotable" => null,
"is_video" => null,
"closeup_description" => null
);

0

Решение

В результате вы получаете жонглирование типов PHP при слабом сравнении значений другого типа.

Попробуйте это, например:

$x = ('Irix' == 0 );
var_export( $x );

Ты получаешь TRUE !

Зачем?

'Irix' превращается в intпосле преобразования 0 так что сравнивается с 0,

В вашем массиве у вас есть несколько значений 0 вот почему Irix видимо найден.

Вы должны использовать строгий сравнение при вызове функции:

function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}

return false;
}

Если вам нужно использовать слабое сравнение (чтобы соответствовать 123 == '123' например) вы можете настроить функцию для приведения числа к строкам и выполнить слабое сравнение:

function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
// cast $item to string if numeric when doing weak comparison
if( ! $strict && is_string( $needle ) && ( is_float( $item ) || is_int( $item ) ) ) {
$item = (string)$item;
}
// ----------------------------------------------------------

if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}

return false;
}

Наконец, если вам нужно также оценить истинные совпадения подстрок (например, find "example" в строку "this is a example") функция такая:

function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
// cast $item to string if numeric when doing weak comparison
if( ! $strict && is_string( $needle ) && ( is_float( $item ) || is_int( $item ) ) ) {
$item = (string)$item;
}
// ----------------------------------------------------------

// Substring search
if( is_string( $needle ) && is_string( $item ) && strpos( $item, $needle ) !== false ) {
return true;
}
// ----------------

if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}

return false;
}

Конкурировать демо-код доступен Вот

1

Другие решения

Других решений пока нет …

По вопросам рекламы [email protected]