簡體   English   中英

如何在 Laravel 中獲取和更改元素數組的值?

[英]How to get and change value of element array in Laravel?

我有 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]

在 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

試試這個代碼

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

echo $array_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  
    }
    else
    {
        //do nothing
    }
    $index++;

}

echo "<pre>";
print_r($array_2);
echo "</pre>";

我猜你只想替換 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;
    }
}

以下 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函數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM