我试图遍历这些数组项并仅从url
个项中获取数据,并将所有收集的数据添加到新数组中。
我正在尝试实现的步骤:
1.遍历$event['lineups']
(4个项目)。
2.遍历事件内部的数据(每个6项)
3.从每一项中获取以下内容:
facebook_page_url
,instagram_page_url
,official_website_url
array (size=4)
0 =>
array (size=6)
'id' => string '22007301-f49f-442d-b93f-4c7ce5cbc8de' (length=36)
'name' => string 'MC Bassman' (length=10)
'facebook_page_url' => string 'https://www.facebook.com/bassmansdc/' (length=36)
'instagram_page_url' => string 'https://www.instagram.com/mcbassman_sdc/' (length=40)
'official_website_url' => string '' (length=0)
'position' => int 1
1 =>
array (size=6)
'id' => string 'f4c41b6f-33a1-4da0-b7fa-ffdfbd84724d' (length=36)
'name' => string 'Indika' (length=6)
'facebook_page_url' => string 'https://www.facebook.com/INDIKAMCR/' (length=35)
'instagram_page_url' => string 'https://www.instagram.com/indikamcr/' (length=36)
'official_website_url' => null
'position' => int 2
我的尝试和代码:
设置我们需要从中获取数据的键:
$default_keys = [
'facebook_page_url',
'instagram_page_url',
'official_website_url',
];
创建一个新数组以将数据添加到:
$performer_urls = [];
遍历数组$event['lineups']
中的每个array (size=4)
项目
foreach( $event['lineups'] as $lineups ) {
遍历数组中的每个值:array (size=6)
foreach( $lineups as $lineup ) {
检查数据是否存在,如果存在,则用键和数据更新$performer_urls
数组。
if ( isset( $lineup[ $key ] ) && ! empty( $lineup[ $key ] ) ) {
$performer_urls[$key] = $event['lineups'][ $key ];
}
到目前为止的完整代码:
$default_keys = [
'facebook_page_url',
'instagram_page_url',
'official_website_url',
];
$performer_urls = [];
foreach( $event['lineups'] as $lineups ) {
foreach( $lineups as $lineup ) {
// Example: $contact_details['address_line_1']
if ( isset( $lineup[ $key ] ) && ! empty( $lineup[ $key ] ) ) {
// Update array (example): $address['address_line_1'] = $contact_details['address_line_1']
$performer_urls[$key] = $event['lineups'][ $key ];
}
}
}
var_dump($performer_urls);
Notice: Undefined variable: key in
我现在遇到的错误是指使用了未定义的$key
变量,但希望您能在这里和几乎那里看到我正在尝试实现的目标?
答案 0 :(得分:0)
我相信我想出了一个解决方案,我明白了您的想法,但是恐怕您的代码中存在一些问题。
我刚刚重构了它们,最重要的是,我不明白您打算如何精确地填充新的$performer_urls
数组而不覆盖键,这就是为什么我选择仅使用{ {1}}语法。
首先,是的,PHP抱怨您的[ ]
未定义变量:-)示例是正确的:
然后我重构了错误的部分(如我所知),下面是完整的代码:
$key
我有这个:
<?php
$event['lineups'] = [
[
'id' => '22007301-f49f-442d-b93f-4c7ce5cbc8de',
'name' => 'MC Bassman',
'facebook_page_url' => 'https://www.facebook.com/bassmansdc/',
'instagram_page_url' => 'https://www.instagram.com/mcbassman_sdc/',
'official_website_url' => '',
'position' => 1,
],
[
'id' => 'f4c41b6f-33a1-4da0-b7fa-ffdfbd84724d',
'name' => 'Indika',
'facebook_page_url' => 'https://www.facebook.com/INDIKAMCR/',
'instagram_page_url' => 'https://www.instagram.com/indikamcr/',
'official_website_url' => null,
'position' => 2,
],
];
$default_keys = [
'facebook_page_url',
'instagram_page_url',
'official_website_url',
];
$performer_urls = [];
foreach ($event['lineups'] as $lineups) {
foreach ($lineups as $key => $value) {
if (in_array($key, $default_keys) && !empty($value)) {
$performer_urls[] = $value;
}
}
}
var_dump($performer_urls);