我试图从以下
获取stocklevels的计数和值Array ( [barcodes] => Array ( [barcode] => 10011010009 ) [basePrice] => 25.00 [customFields] => Array ( ) [description] => CBC-CBCJSW [discontinued] => false [PLU] => CBC Boy's Shirt 20 [priceLevels] => Array ( ) [primaryCategory] => CBC- Boys Shirts [productLineName] => CBC Boy's Shirt 20 [promptPOSOperatorForPrice] => false [sellByWeightOption] => false [stock] => Array ( [stockLevel] => Array ( [0] => Array ( [outletExportCode] => Level1 [stockCount] => 500.000000 ) [1] => Array ( [outletExportCode] => Level2 [stockCount] => 1000.000000 ) ) ) [taxes] => Array ( [taxName] => GST ) )
我尝试过以下操作,即使数组中有2个级别,我也会一直得1:
count($ra['stock']['stockLevel']['stockCount']);
count($ra['stock']['stockLevel']);
另外,我试图循环搜索结果以获得库存,但它似乎不起作用:
$stockLevelArr[] = $ra['stock'];
$totalStock = 0;
for($i=0;$i<count($stockLevelArr);$i++){
echo $ra['productLineName'] . ' - Stock outside IF: ' . (int) $stockLevelArr[$i]['stockLevel']['stockCount'];
echo '<br>';
if (isset($stockLevelArr[$i]['stockLevel']['stockCount'])) {
$totalStock = $totalStock + $stockLevelArr[$i]['stockLevel']['stockCount'];
}
}
echo 'Stock count: ' . $totalStock;
echo '<br>';
var dump
array(13) { ["barcodes"]=> array(1) { ["barcode"]=> string(11) "10011010009" } ["basePrice"]=> string(5) "25.00" ["customFields"]=> array(0) { } ["description"]=> string(10) "CBC-CBCJSW" ["discontinued"]=> string(5) "false" ["PLU"]=> string(18) "CBC Boy's Shirt 20" ["priceLevels"]=> array(0) { } ["primaryCategory"]=> string(16) "CBC- Boys Shirts" ["productLineName"]=> string(18) "CBC Boy's Shirt 20" ["promptPOSOperatorForPrice"]=> string(5) "false" ["sellByWeightOption"]=> string(5) "false" ["stock"]=> array(1) { ["stockLevel"]=> array(2) { [0]=> array(2) { ["outletExportCode"]=> string(13) "Tara Uniforms" ["stockCount"]=> string(10) "500.000000" } [1]=> array(2) { ["outletExportCode"]=> string(3) "CBC" ["stockCount"]=> string(11) "1000.000000" } } } ["taxes"]=> array(1) { ["taxName"]=> string(3) "GST" } }
我将不胜感激。
更新:以下工作。感谢大家的回复和帮助。
$totalStock = 0;
$times_found = 0;
$stock = $ra['stock'];
foreach($stock['stockLevel'] as $stock_level) {
if(isset($stock_level['stockCount'])) {
$times_found++;
$totalStock = $totalStock + $stock_level['stockCount'];
}
}
答案 0 :(得分:1)
我假设你想知道数组中stockCount
多少次?如果是这样,我将使用数组循环遍历数组的每个索引,并在每次找到它时递增一个变量。例如:
$times_found = 0;
foreach($ra['stock'] as $stock) {
foreach($stock['stockLevel'] as $stock_level) {
if(isset($stock_level['stockCount'])) {
$times_found++;
}
}
}
答案 1 :(得分:1)
您应该计算递归以获取计数中的所有键:
count($ra, COUNT_RECURSIVE);
另请参阅php手册https://www.php.net/manual/en/function.count.php
我认为你应该将你的for循环更改为:
<?php
$totalStock = 0;
foreach ($ra['stock'] as $stock) {
echo $ra['productLineName'] . ' - Stock outside IF: ' . (int) $stock['stockLevel']['stockCount'];
echo '<br>';
if (isset($stock['stockLevel']['stockCount'])) {
$totalStock = $totalStock + $stock['stockLevel']['stockCount'];
}
}
echo 'Stock count: ' . $totalStock;
echo '<br>';
而不是for循环,不知道你为什么使用它,你最好在这个例子中使用foreach。