gpt4 book ai didi

php - 将多维数组转换为单维数组

转载 作者:可可西里 更新时间:2023-10-31 23:38:49 24 4
gpt4 key购买 nike

我正在使用 yii2 php 框架,我在访问 db 中的所有用户时有这个查询:

$allUsersQuery = new Query;
$allUsersQuery->select(['_id'])->from('user')->where([ 'parent' => new \MongoId($session['company_owner']) ]);
$allUsers = $allUsersQuery->all();

当我var_dump $allUsers 数组时,它给我这个输出:

array (size=5)
0 =>
array (size=1)
'_id' =>
object(MongoId)[147]
public '$id' => string '55d5a227650fc90c35000044' (length=24)
1 =>
array (size=1)
'_id' =>
object(MongoId)[148]
public '$id' => string '55d5a22a650fc90c35000047' (length=24)
2 =>
array (size=1)
'_id' =>
object(MongoId)[149]
public '$id' => string '55d5a22a650fc90c3500004a' (length=24)
3 =>
array (size=1)
'_id' =>
object(MongoId)[150]
public '$id' => string '55d5a22b650fc90c3500004d' (length=24)
4 =>
array (size=1)
'_id' =>
object(MongoId)[151]
public '$id' => string '55d5a22b650fc90c35000050' (length=24)

它是多维数组。我已经搜索并尝试了几种解决方案,但它们只给我这个结果:

array (size=1)
'_id' =>
object(MongoId)[147]
public '$id' => string '55d5a227650fc90c35000044' (length=24)

以下是我尝试过但未能奏效的几个解决方案:
1.

function array_flatten($allUsers) { 
if (!is_array($allUsers)) {
return FALSE;
}
$allUsersResult = array();
foreach ($allUsers as $key => $value) {
if (is_array($value)) {
$allUsersResult = array_merge($allUsersResult, array_flatten($value));
}
else {
$allUsersResult[$key] = $value;
}
}
return $allUsersResult;
}

2.

array_reduce($allUsers, 'array_merge', array());

3.

$allUsers = $allUsers[0];

我的预期输出是:

Array('value1', 'value2', 'value3');

我如何使它起作用?

最佳答案

您可以简单地遍历数组并收集这些数据。
我刚刚编辑了您的功能:

function array_flatten($allUsers) { 
if (!is_array($allUsers)) { return FALSE; }

$allUsersResult = array();
foreach ($allUsers as $key => $value) {
if (!is_array($value)) { return FALSE; }

$allUsersResult[] = $value["_id"]->{'$id'};
}
return $allUsersResult;
}

关于php - 将多维数组转换为单维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33139597/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com