簡體   English   中英

PHP或Laravel Helper函數將變量收集到數組中

[英]PHP or Laravel Helper Function to Collect Variables Into Array

我依稀記得有一個PHP或Laravel幫助函數,它使用變量名作為數組鍵將變量收集到命名數組中。

那個功能的名稱又是什么?

$foo = 1;
$bar = 2;

這個電話

some_function($foo, $bar);

會回來的

[
    "foo" => 1,
    "bar" => 2
]

使用compact()

compact('foo', 'bar');

使用combine()

combine方法將集合的鍵與另一個數組或集合的值combine在一起:

$collection = collect(['name', 'age']);

$combined = $collection->combine(['George', 29]);

$combined->all();

// ['name' => 'George', 'age' => 29]

您可以使用PHP函數array_combine,請訪問這些鏈接array_combine

$array_key = ['name','age'];

$array_value = ['George', 29];

$final_array = array_combine($array_key,$array_value);

你會得到最終結果

[
    "name" => "George",
    "age" => 29
]

注意: - 兩個數組必須與數組大小相同

暫無
暫無

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

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