我正在尝试计算从脚本返回的数组的结果。 我有两种情况可以找回选项a
Array ( [Id] => 1779 [SupplierId] => 1809 [SupplierName] => cccccc)
第二个选项ib
Array (
[0] => Array ( [Id] => 2020 [SupplierId] => 1809 [SupplierName] => vvv)
[1] => Array ( [Id] => 2058 [SupplierId] => 1809 [SupplierName] => bbb)
[2] => Array ( [Id] => 2063 [SupplierId] => 1809 [SupplierName] => xx)
)
如果我确实相信我回来的情况3 我如何计算选项A中我回到1,而在选项B中我会回来3?
答案 0 :(得分:2)
您可以创建如下函数:
function countRes($arr) {
return is_array(end($arr)) ? count($arr) : 1;
}
$arr1 = array("Id" => 1779, "SupplierId" => 1809, "SupplierName" => "cccccc");
$arr2 = array(array("Id" => 2020, "SupplierId" => 1809, "SupplierName" => "vvv"),
array("Id" => 2058, "SupplierId" => 1809, "SupplierName" => "bbb"),
array("Id" => 2063, "SupplierId" => 1809, "SupplierName" => "xx"));
echo countRes($arr1); // 1
echo countRes($arr2); // 3
它检查最后一个元素是否是一个数组,并返回结果数组中的数组数。否则返回1,因为结果数组本身包含数据。
答案 1 :(得分:0)
首先,评论。 方法应始终返回相同类型的对象。如果您可以修改脚本代码以始终返回数组数组,请执行此操作。
如果你做不到,那么hacky解决方案就是有序的。
你可以使用php的typeof运算符来查找第一个数组中的元素是整数还是更多数组:
答案 2 :(得分:0)
$array1 = array ( 'Id' => 1779, 'SupplierId' => 1809, 'SupplierName' => 'cccccc');
$array2 = array(
array ( 'Id' => 1779, 'SupplierId' => 1809, 'SupplierName' => 'cccccc'),
array ( 'Id' => 1779, 'SupplierId' => 1809, 'SupplierName' => 'cccccc'),
array ( 'Id' => 1779, 'SupplierId' => 1809, 'SupplierName' => 'cccccc')
);
// sub arrays with key
$array3 = array(
'first'=>array ( 'Id' => 1779, 'SupplierId' => 1809, 'SupplierName' => 'cccccc'),
'second'=>array ( 'Id' => 1779, 'SupplierId' => 1809, 'SupplierName' => 'cccccc'),
'third'=>array ( 'Id' => 1779, 'SupplierId' => 1809, 'SupplierName' => 'cccccc')
);
echo arrayCount($array3);
function arrayCount($array){
foreach($array as $key=>$value){
if(is_array($value)){
return count($array);
}else{
return 1;
}
}
}