Php 需要帮助修复我的使用对象代码创建多维数组吗
我有以下格式的Json数据:Php 需要帮助修复我的使用对象代码创建多维数组吗,php,arrays,loops,Php,Arrays,Loops,我有以下格式的Json数据: stdClass Object ( [sources] => Array ( [0] => stdClass Object ( [id] => 147 [name] => CatsWhoCode.com [segments] =>
stdClass Object
(
[sources] => Array
(
[0] => stdClass Object
(
[id] => 147
[name] => CatsWhoCode.com
[segments] => Array
(
[0] => stdClass Object
(
[id] => 104
[name] => Default
[style] => EDUCATIONAL
[targetAudience] => KNOWLEDGEABLE
[isPrimary] => 1
)
)
)
[1] => stdClass Object
(
[id] => 181
[name] => Inspire Trends - Your Daily Dose of Design and Development Resources
[segments] => Array
(
[0] => stdClass Object
(
[id] => 146
[name] => Inspire Trends
[style] => TECHNICAL
[targetAudience] => KNOWLEDGEABLE
[isPrimary] => 1
)
[1] => stdClass Object
(
[id] => 147
[name] => Inspire Trends
[style] => EDUCATIONAL
[targetAudience] => KNOWLEDGEABLE
[isPrimary] => 0
)
)
)
[2] => stdClass Object
(
[id] => 182
[name] => Designmodo
[segments] => Array
(
[0] => stdClass Object
(
[id] => 148
[name] => Design Modo
[style] => INFORMAL
[targetAudience] => KNOWLEDGEABLE
[isPrimary] => 1
)
[1] => stdClass Object
(
[id] => 149
[name] => Design Modo
[style] => INFORMATIVE
[targetAudience] => GENERAL
[isPrimary] => 0
)
)
)
)
[status] => 10
)
我正在尝试对其进行过滤并创建(多维)数组,该数组应如下所示:
Array
(
[CatsWhoCode.com] => Array
(
[104] => [PRI] Default
)
[Inspire Trends - Your Daily Dose of Design and Development Resources] => Array
(
[146] => [PRI] Inspire Trends
[147] => Inspire Trends
)
[Designmodo] => Array
(
[148] => [PRI] Design Modo
[149] => Design Modo
)
)
但从我的代码中,我最终得到以下结果:
Array
(
[CatsWhoCode.com] => Array
(
[0] => Array
(
[104] => [PRI] Default
)
)
[Inspire Trends - Your Daily Dose of Design and Development Resources] => Array
(
[0] => Array
(
[146] => [PRI] Inspire Trends
)
[1] => Array
(
[147] => Inspire Trends
)
)
[Designmodo] => Array
(
[0] => Array
(
[148] => [PRI] Design Modo
)
[1] => Array
(
[149] => Design Modo
)
)
)
这是我的代码,我不知道如何修复它
function ar_audienceList($AR){
$audienceList = $AR->getAudienceList();
foreach ($audienceList->sources AS $key => $source){
foreach($source->segments AS $v){
if ($v->isPrimary == 1)$pri = "[PRI]";
$options[$source->name][] = array($v->id => $pri." ".$v->name,);
$pri = ''; // reset primary
}
}
return $options;
}
谢谢不要将
$options[$source->name]
中的每个元素索引到下一个可用的索引([]
),而是将其索引到$source->segments
([$v->id]
)的id
这是我真正想要的(虽然它仍然不是一个很好的标题,因为它没有描述你的问题)。非常感谢你,这很有效。我以前试过这个,但没有真正起作用$选项[$source->name][$v->id]=数组($pri.“$v->name);非常感谢。谢谢,还是解释一下吧。
function ar_audienceList($AR)
{
$audienceList = $AR->getAudienceList();
foreach ($audienceList->sources as $key => $source)
{
foreach($source->segments AS $v)
{
if ($v->isPrimary == 1)
{
$pri = "[PRI]";
}
$options[$source->name][$v->id] = $pri." ".$v->name; // Change is here
$pri = ''; // reset primary
}
}
return $options;
}