如何从while循环中创建逗号分隔的列表?

时间:2019-11-10 11:12:12

标签: php while-loop comma

$personas = [
'Hermann' => [
  'status' => '0',
  'gender' => 'maskulin'
],
'Lida' => [
  'status' => '1',
  'gender' => 'feminin'
],
'Susi' => [
  'status' => '0',
  'gender' => 'feminin'
],
'Mara' => [
  'status' => '0',
  'gender' => 'feminin'
]
];

状态为0的人物角色

  echo 'Personas with status 0: ';
  while ($status = current($personas)) {
    if ($status['status'] == '0') {
    $status_list = key($personas);
    echo $status_list;

  }
  next($personas);
}

结果是: 状态为0的角色:HermannSusiMara

预计为: 状态为0的角色:Hermann,Susi,Mara

3 个答案:

答案 0 :(得分:3)

为您提供一些不同的解决方案。

$statusZeroPersonae = [];

foreach($personas as $personaName => $persona) {
    if ($persona['status'] === '0') {
        $statusZeroPersonae[] = $personaName;
    }
}

echo 'Personae with status 0: ' . implode(", ", $statusZeroPersonae);

答案 1 :(得分:0)

implode()函数对于此类事情非常方便...

我还自由地清理了一下代码:

<?php
$personas = [
  'Hermann' => [
    'status' => '0',
    'gender' => 'maskulin'
  ],
  'Lida' => [
    'status' => '1',
    'gender' => 'feminin'
  ],
  'Susi' => [
    'status' => '0',
    'gender' => 'feminin'
  ],
  'Mara' => [
    'status' => '0',
    'gender' => 'feminin'
  ]
];

echo 'Personas with status 0: ';
while ($status = current($personas)) {
  if ($status['status'] == '0') {
    $personaName = key($personas);
    $personasWithStatus0[] = $personaName;
  }
  next($personas);
}
echo implode(", ", $personasWithStatus0);

输出显然是:

  

状态为0的人物:赫尔曼,苏西,玛拉

答案 2 :(得分:0)

您可以将它们保留在数组中,并使用joinimplode

while ($status = current($personas)) {
  if ($status['status'] == '0') {
   $result[] = key($personas);
 }
 next($personas);
}
echo 'Personas with status 0: '.join(', ',$result);

工作示例:-https://3v4l.org/qjgPC