如何在 Laravel 中获取和更改元素数组的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32774922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get and change value of element array in Laravel?
提问by rome ?
I have 2 arrays:
我有 2 个数组:
$array_1 = [1,2,3,1,2];
$array_1 = [1,2,3,1,2];
and:
和:
$array_2 = [0,0,0,0,0];
$array_2 = [0,0,0,0,0];
I want to change the values of $array_2
, so it will show if the element in $array_1
is number 1 or 2 only.
我想更改 的值$array_2
,因此它会显示中的元素$array_1
是编号 1 还是编号 2。
foreach($array_1 as $item)
{
if($item = 1 || $iten == 2)
{
$index = ...;//how to get index of this element
$array_2[$index] = 1; //I don't sure this syntax is right
}
}
Output $array_2
should look like: $array_2 = [1,1,0,1,1]
输出$array_2
应如下所示:$array_2 = [1,1,0,1,1]
采纳答案by Ankur Tiwari
<?php
// your code goes here
$array_1 = [1,2,3,1,2];
$array_2 = [0,0,0,0,0];
$index = 0;
foreach($array_1 as $item)
{
if($item == 1 || $item == 2)
{
//how to get index of this emlement
$array_2[$index] = 1; //I don't sure this syntax is right
$index++;
}
else
{
//do nothing
$index++;
}
}
echo "<pre>";
print_r($array_2);
echo "</pre>";
回答by Deividson Calixto
In Laravel 5 or above, you can do this:
Just pass a array to this function, use a dot notation to handle nested arrays
在 Laravel 5 或更高版本中,您可以这样做:
只需将数组传递给此函数,使用点符号处理嵌套数组
use Illuminate\Support\Arr;
Arr::set($data, 'person.name', 'Calixto');
Or you can use this Laravel Helpers:
或者你可以使用这个 Laravel 助手:
$data = ['products' => ['desk' => ['price' => 100]]];
data_set($data, 'products.desk.price', 200, false);
For more details look at laravel documentation: Laravel Docs Helpers
有关更多详细信息,请查看 Laravel 文档: Laravel Docs Helpers
回答by jitendrapurohit
Try this code
试试这个代码
$array_1 = array(1,2,3,1,2);
foreach($array_1 as &$item)
{
if($item = 1 || $item == 2) {
$item = 1;
}
}
echo $array_1;
回答by Chris
The following PHP code might do what you intend:
以下 PHP 代码可能符合您的意图:
<?php
$valid = [1, 2]; // allows you to extend a bit later
$array_1 = [1,2,3,1,2];
$array_2 = array_map(function($var) use ($valid) {
return in_array($var, $valid) ? 1 : 0;
}, $array_1);
print_r($array_2); // [1, 1, 0, 1, 1]
Take a look at the array_map
function at http://php.net/manual/en/function.array-map.php
array_map
在http://php.net/manual/en/function.array-map.php看一下函数
回答by MaK
I guess you only want to replace items other than 1, 2 to 0, Correct me if I am wrong.
我猜你只想替换 1、2 到 0 以外的项目,如果我错了,请纠正我。
$array_3 = array();
foreach ($array_1 as $key => $item)
{
if($item == 1 || $item == 2)
{
$array_3[$key] = $item;
}
else
{
$array_3[$key] = 0;
}
}