php从数组中获取特定的查询信息

时间:2013-01-23 14:03:21

标签: php sql-server arrays loops foreach

 <?php

echo "Connecting Database <br>";
$server = 'UKVDEMO03'; //Here you're server
$database = 'smtpFetch';//here the database you want to connect to
$user = 'shoaibsg';//here te user WHO HAS THE RIGHT PERMISSIONS AT THE DATABASE
$pass = '1111111';//and here the user's password
$dsn = "Driver={SQL Server};Server=$server;Database=$database;";
$connect = odbc_connect($dsn, $user, $pass); 
echo "Successfully connected....";

//getting subscribe user detail
$subQuery="select emailAddress, dataSet from userDetail";
$subRes=odbc_exec($connect, $subQuery);
$ix=odbc_num_rows($subRes);
//$newArray[]=$newArray array;
$row[]=array();
$newArrayD[]=$row;
$i=0;
$xc=0;
if($ix>0)
{

    while($row=odbc_fetch_array($subRes))
    {
            $newArrayD[$row['emailAddress']] =$row['emailAddress'];
            $newArrayD[$row['dataSet']] =$row['dataSet'];
    }

}
foreach($newArrayD as $arrayD)
{ $i++; 
echo "<br> -" . $arrayD;
echo "-i increment -" . $i;
}


?>

以上显示以下输出

- 阵列  -shoaib@xyz.com  -SSCRUS_CS2002  -nick@xyz.com  -SSCE_CS2002

现在问题是:如果我只需要在foreach循环中只显示emailAddress,它只会显示第一个字符(我在foreach循环中使用了下面的代码)

echo "<br> -" . $arrayD['emailAddress'];

如上面的输出显示为   -  -s  -S  -n  -S

我很困惑,请帮助

1 个答案:

答案 0 :(得分:0)

生成阵列的代码已关闭。试试这个:

while ($row=odbc_fetch_array($subRes))
{
    $newArrayD[$row['dataSet']] = $row['emailAddress'];
    // This would generate for example $newArrayD['SSCRUS_CS2002'] = 'shoaib@xyz.com'
}

然后,要显示它们,请遍历数组:

foreach ($newArrayD as $dataset=>$emailaddress)
{
    echo "- $emailaddress<br />";
}

编辑 - 要将它们保存在单独的数组中:

$newArrayD = array('dataset' => array(), 'emails' => array());

while ($row=odbc_fetch_array($subRes))
{
    $newArrayD['dataset'][] = $row['dataSet'];
    $newArrayD['emails'][] = $row['emailAddress'];
}

要遍历电子邮件:

foreach ($newArrayD['emails'] as $emailaddress)
{
    // Code you wish to execute
}

迭代数据集:

foreach ($newArrayD['dataset'] as $dataset)
{
    // Code you wish to execute
}

使用此方法,$newArrayD['dataset'][0]将是与$newArrayD['emails'][0]等相关联的数据集。