如何在Laravel中获取和更改元素数组的值?

时间:2015-09-25 04:40:48

标签: php arrays laravel indexing

我有2个阵列:

$array_1 = [1,2,3,1,2];

$array_2 = [0,0,0,0,0];

我想更改$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  
    }
}

输出$array_2应如下所示:$array_2 = [1,1,0,1,1]

5 个答案:

答案 0 :(得分:2)

在Laravel 5或更高版本中,您可以执行以下操作:
只需将数组传递给此函数,使用点表示法即可处理嵌套数组

use Illuminate\Support\Arr;
Arr::set($data, 'person.name', 'Calixto');

或者您可以使用以下Laravel帮助器:

$data = ['products' => ['desk' => ['price' => 100]]];
data_set($data, 'products.desk.price', 200, false);

有关更多详细信息,请参阅laravel文档: Laravel Docs Helpers

答案 1 :(得分:1)

<?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>";

答案 2 :(得分:0)

试试此代码

$array_1 = array(1,2,3,1,2);
foreach($array_1 as &$item)
{
  if($item = 1 || $item == 2) {
    $item = 1;
  }
}

echo $array_1;

答案 3 :(得分:0)

我猜你只想将1,2以外的物品替换为0,如果我错了,请纠正我。

   DEBUG = False
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    STATIC_ROOT = 'staticfiles'
    STATIC_URL = '/static/'

    STATICFILES_DIRS = (
        os.path.join(BASE_DIR, 'static'),
    )

答案 4 :(得分:0)

以下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]

查看http://php.net/manual/en/function.array-map.php

处的array_map功能
相关问题