laravel 将数组转换为字符串数组

mgdq6dx1  于 2022-12-27  发布在  其他
关注(0)|答案(4)|浏览(326)
array:5 [
  0 => array:1 [
    "location_id" => 1
  ]
  1 => array:1 [
    "location_id" => 4
  ]
  2 => array:1 [
    "location_id" => 6
  ]
  3 => array:1 [
    "location_id" => 7
  ]
  4 => array:1 [
    "location_id" => 8
  ]
]

将其转换为[“1”、“4”、“6”、“7”、“8”、]
如在不同查询中使用此[“1”,“4”,“6”,“7”,“8”,]数组

z9smfwbn

z9smfwbn1#

您可以使用Laravel Collection pluck方法,从每个数组项中只返回您想要的属性,然后将结果数组扁平化为flatten

$data = [
    [
        "location_id" => 1
    ],
    [
        "location_id" => 4
    ],
    [
        "location_id" => 6
    ],
    [
        "location_id" => 7
    ],
    [
        "location_id" => 8
    ]
];

$result = collect($data)->pluck('location_id')->flatten();
ee7vknir

ee7vknir2#

欢迎来到斯塔克弗鲁德。

**您可以使用laravel辅助器数组扁平化方法:**从此处阅读更多信息:https://laravel.com/docs/9.x/helpers#method-array-flatten

// Add the helper class call in the controller header
use Illuminate\Support\Arr;

// The actual array
$array = [
    0 => [
        "location_id" => 1
    ],
    1 =>  [
        "location_id" => 4
    ],
    2 =>  [
        "location_id" => 6
    ],
    3 =>  [
        "location_id" => 7
    ],
    4 =>  [
        "location_id" => 8
    ]
];

// Flatten the array function
$result = Arr::flatten($array);

结果:

['1','4','6','7','8']
kuarbcqp

kuarbcqp3#

虽然没有你想要的那么干净,但还是可以完成工作的。

$resultSet = collect($data)->map(function($item){
    return $item['location_id'];
})->toArray();

$resultString = "[";
foreach($resultSet as $item){
    $resultString .= "'{$item}'" . ",";
}
$resultString = rtrim($resultString, ","); // produces this: "['1','4','6','7','8']"

$resultString .= "]";

dd($resultString);
dly7yett

dly7yett4#

你可以使用laravel helper数组pluck方法从这里阅读更多关于它的信息:https://laravel.com/docs/9.x/helpers#method-array-pluck

$data   = \Arr::pluck($array, 'location_id'); 
$result = array_map('strrev', $data); 
// ["1","4","6","7","8"]

相关问题