【问题标题】:Printing single item of multidimensional arrays打印单项多维数组
【发布时间】:2023-03-18 04:09:01
【问题描述】:

我的多维数组有问题。我在这里遇到了两个问题:当我打印我的数组时,我得到了每个对象两次。我的下一个问题是我想得到一个列的结果,例如:[strProductNaam] => 可调哑铃 - Bowflex 552i - 2 到 24 公斤。有人可以帮我吗?

提前致谢!

<?php

require('php/connection.php');

$sql = "SELECT * FROM tblProduct";
$result = sqlsrv_query($conn,$sql);


if( $result === false ) {
     die( print_r( sqlsrv_errors(), true));
}

 while($row = sqlsrv_fetch_array($result)) {
        $datas[] = $row;
    }

echo '<pre>';
print_r($datas);
echo '</pre>';



foreach($datas as $data){
  echo $data['strProductNaam'] ." ";
}

sqlsrv_free_stmt($result);
sqlsrv_close($conn);

?>

之后的结果:print_r($datas):

Array
(
    [0] => Array
        (
            [0] => 1
            [ID] => 1
            [1] => 1
            [CategorieID] => 1
            [2] => Adjustable Dumbbells - Bowflex 552i - 2 to 24 kg 
            [strProductNaam] => Adjustable Dumbbells - Bowflex 552i - 2 to 24 kg 
            [3] => 499
            [intPrijs] => 499
            [4] =>  Easy to adjust

            [strPlusPunt1] =>  Easy to adjust

            [5] => Saving space
            [strPlusPunt2] => Saving space
        )

    [1] => Array
        (
            [0] => 2
            [ID] => 2
            [1] => 1
            [CategorieID] => 1
            [2] => Dumbbell 15kg
            [strProductNaam] => Dumbbell 15kg
            [3] => 28.95
            [intPrijs] => 28.95
            [4] => Easy to expand

            [strPlusPunt1] => Easy to expand

            [5] => Easily adjustable
            [strPlusPunt2] => Easily adjustable
        )

【问题讨论】:

  • 我想得到一列的结果,例如:[strProductNaam]你有一个foreach,它不起作用吗?

标签: php arrays sql-server multidimensional-array


【解决方案1】:

sqlsrv_fetch_array 中传递SQLSRV_FETCH_ASSOC 作为第二个参数。这将只返回命名键,并删除数字。

while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
    $datas[] = $row['strProductNaam'];
}

【讨论】:

  • 那行得通。谢谢!以及如何只选择一项 strProductNaam?
  • 有几种方法。低于print_r($data[0]) 个人我更喜欢current($data) (php.net/manual/en/function.current),因为它获取当前指针位置并且不依赖于知道密钥。
【解决方案2】:

这是解决方案:

while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
   $datas[] = $row;
}
echo '<pre>';
print_r($datas[1]['strProductNaam']);
echo '</pre>';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 2016-11-28
    相关资源
    最近更新 更多