Php 如何正确显示更深的数组值?
我很难用PHP访问数组的深层部分并在页面上以某种方式显示它 我试图用城市和计数显示这样的数据:Php 如何正确显示更深的数组值?,php,arrays,Php,Arrays,我很难用PHP访问数组的深层部分并在页面上以某种方式显示它 我试图用城市和计数显示这样的数据: Mobile (3) Auburn (2) 这是我的阵列: Array ( [0] => Array ( [0] => Array ( [city] => Mobile [numLocations] => 3 ) [1] =
Mobile (3)
Auburn (2)
这是我的阵列:
Array
(
[0] => Array
(
[0] => Array
(
[city] => Mobile
[numLocations] => 3
)
[1] => Array
(
[city] => Auburn
[numLocations] => 2
)
)
)
这是我到目前为止所拥有的。这只是显示单词“Array”
while($row = mysqli_fetch_assoc($result)){
$state = $row['state'];
$stateAbv = $row['stateAbv'];
$city = $row['city'];
$numSLocations = $values['cnt'];
if (!isset($rows[$row['state']])){
$rows[$row['state']] = array();
}
$rows[$row['state']][] = ['city' => $city, 'numLocations' => $numLocations];
}
foreach($rows as $state => $cities){
echo array_column($cities, 'numLocations'));
}
我试图用一个城市和一个计数来显示这样的数据:
Mobile (3)
Auburn (2)
流动电话(3)
奥本(2)
未经测试
while($row = mysqli_fetch_assoc($result)){
if (!isset($rows[$row['state']])) $rows[$row['state']] = 0; //initialize with 0
$rows[$row['state']] += $row['cnt']; //increment the num Stores
}
行应该是这样的:
['Mobile' => 3, 'Auburn' => 2]
您也有这个问题($values):
换句话说,什么是$values
,没有更多的上下文,就无法知道这是什么。我假设你的意思是$row
然后(如果你真的想用()和2行返回。)
输出
Mobile (3)
Auburn (2)
如果您试图转换该数组,我不知道这与此有什么关系(MySql结果):
这仅在city
是唯一的且不执行增量时有效
这只是显示单词“Array”
while($row = mysqli_fetch_assoc($result)){
$state = $row['state'];
$stateAbv = $row['stateAbv'];
$city = $row['city'];
$numSLocations = $values['cnt'];
if (!isset($rows[$row['state']])){
$rows[$row['state']] = array();
}
$rows[$row['state']][] = ['city' => $city, 'numLocations' => $numLocations];
}
foreach($rows as $state => $cities){
echo array_column($cities, 'numLocations'));
}
当然,因为array\u column
返回一个数组(如我刚才所示),并且您不能回显一个数组,您可以,但它只会说“array”。这正是它在本代码中所做的:
foreach($rows as $state => $cities){
echo array_column($cities, 'numLocations')); //returns an array
}
因此,改用print\u r
或var\u export
等。。。上述结果将类似于:
[0 => 3,1 => 2]
基本上是这样的:
array_column($array[0], 'numLocations')
干杯 感觉只有第一个索引,可以通过
array\u shift
$row = array_shift($row);
// now fetch both the data.
$temp = array_column('numLocations','city');
foreach($temp as $k => $v){
$result[] = $k.'('.$v.')';
}
这应该可以解决您的问题。查看手册,array列返回一个值数组,但您也松开了键-您需要重新考虑您的方法,或者可能是array列和array列-我不完全确定最终结果是什么您的代码和数组不匹配-
$rows[$row['state'][]['city'=>$city,'numLocations'=>$numStores];
该数组中没有键。$numSLocations=$values['cnt'];
未定义$values
。。。。
$row = array_shift($row);
// now fetch both the data.
$temp = array_column('numLocations','city');
foreach($temp as $k => $v){
$result[] = $k.'('.$v.')';
}