简体   繁体   English

使用PHP中的键/值将元素添加到数组中?

[英]Adding elements to an array using key/value in PHP?

I know I can add elemnts to an array like this: 我知道我可以像这样向数组添加元素:

$arr = array("foo" => "bar", 12 => true);

Now, how can I do that in a foreach using dynamic values? 现在,如何使用动态值在foreach中做到这一点? I have this code: 我有以下代码:

foreach ($values as $value) {

    $imagePath = $value->getImagePath();
    $dependsOn = $value->getDependsOn();
    $dependsOn = explode(':', $dependsOn);
    $dependsOnOptionValueTitle = trim($dependsOn[1]);

    array_push($paths, $dependsOnOptionValueTitle => $imagePath); // not working
}

How can I add key/value pairs to my $paths array? 如何将键/值对添加到$paths数组中?

Instead of 代替

array_push($paths, $dependsOnOptionValueTitle => $imagePath); // not working

you should be able to use 你应该能够使用

$paths[$dependsOnOptionValueTitle] = $imagePath;

From what I can see, this is what you're trying to do: 据我所知,这就是您要尝试执行的操作:

$paths[$dependsOnOptionValueTitle] = $imagePath;

Comment if I'm wrong and I'll try to fix it. 如果我错了,请发表评论,我将尝试修复它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM