用“,”分解一个数组

implode an array with ","

我调用 Proxmox API 来获取每个节点中虚拟机的名称。这部分代码运行良好(我的代码更完整的部分在本 post 末尾):

foreach ($arrays['data'] as $array) {
    echo $array['name'];
}

回声:vm1vm2vm3.

但我想看到这个结果,用逗号分隔:vm1, vm2, vm3.

我试过了:

foreach ($arrays['data'] as $array) {
    echo implode(',', $array['name']);
}

但是错误:"Warning: implode(): Invalid arguments passed in"

所以我尝试了 :

foreach ($arrays['data'] as $array) {
    echo implode(',', (array)$array['name']);
}

没有错误,但没有逗号。结果与简单 "echo $array['name'];"

相同

最后我尝试了 :


foreach ($arrays['data'] as $array) {
    $vmNameWithComma[] = $array['name'];
    echo implode(',', $vmNameWithComma);
}

其中 returns : vm1vm1,vm2vm1,vm2,vm3.

有什么想法吗?

foreach ($servers as $server) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, 'https://'.$onlinenode.'/api2/json/nodes/'.$server['node'].'/qemu');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1);

    $headers = array();
    $headers[] = 'Content-Type: application/json';
    $headers[] = 'Cookie: PVEAuthCookie=' . $cookie;

    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $result = curl_exec($ch);

    if (curl_errno($ch)) {
        echo 'La machine ' .$server['node']. ' est injoignable (erreur : ' . curl_error($ch) . ').<br>';
    }
    else {
        $arrays = json_decode($result, true);
        $vmcount = count((array) $arrays['data']);
        if ($vmcount == 0) {
            echo 'Server ' .$server['node']. ' doesn\'t host vm.<br>';
        }
        else if ($vmcount == 1) {
            echo 'Server ' .$server['node']. ' host only one vm which is : ' .$arrays['data']['0']['name']. '<br>';
        }
        else {
            echo 'Server ' .$server['node']. ' host' .$vmcount. ' vm which are : ';
            foreach ($arrays['data'] as $array) {
                $vmNameWithComma[] = $array['name'];
                echo implode(',', $vmNameWithComma);
            }
            echo '.<br>';
        }
    }
    curl_close($ch);
}

您不需要 foreach 循环。

您需要创建仅包含 name 列的数组,然后对其调用 implode()

$names = array_column($arrays['data'], 'name');
echo implode(',', $names);