有一个PHP脚本使用python脚本获取新数据。
我能够foreach
循环并获取数组的key2和value2,但无法获取$address
和$product
变量以将其放入$ shell命令。我的变量出了什么问题?
刚开始编写代码,如果有人教我这一点将很有帮助。
foreach ($gotdata as $key1 => $value1) {
foreach ($value1 as $key2 => $value2) {
//print " key2: " . $key2 . " value2: ". $value2;
$address = "";
$maker = "";
if($key2 == 'Address'){
$address = $value2;
print "address: ".$address; //able to get it on console
}
if($key2 == 'Product'){
$product = $value2;
print "product: ".$product; //able to get it on console
}
$shell = 'python /opt/getdata.py '.$address.' '.$product;
print "shell:" . $shell; //not able to get $address and $product
// $current = shell_exec($shell);
// $current = (int)$current;
// print "current:" . $current;
}
}
这是多维数组的样子。
每次我运行脚本时,主数组的大小都不同。可能是10或14等。
的
另一方面,子数组始终具有相同的六个项目。
array(2) {
[0]=>
array(6) {
["Id"]=>
string(1) "1"
["Name"]=>
string(15) "name01"
["Address"]=>
string(12) "1.1.1.1"
["Product"]=>
string(1) "1"
["Current"]=>
string(3) "111"
["DateTime"]=>
string(19) "2020-09-09 15:03:46"
}
[1]=>
array(6) {
["Id"]=>
string(1) "2"
["Name"]=>
string(15) "name02"
["Address"]=>
string(12) "1.1.1.2"
["Product"]=>
string(1) "1"
["Current"]=>
string(3) "111"
["DateTime"]=>
string(19) "2020-09-09 15:03:46"
}
答案 0 :(得分:2)
我假设您可以直接从主循环访问所需的值。
编辑:现在已经发布了数组,我确定这可以正常工作。
无需嵌套循环数组
foreach ($gotdata as $key1 => $value1) {
$shell = 'python /opt/getdata.py '.$value1['Address'] . ' ' . $value1['Product'];
print "shell:" . $shell; //not able to get $address and $product
}
嵌套foreach循环与访问子数组项相同。
答案 1 :(得分:-1)
我不知道你的愿望输出是什么。但是,如果您想要两个值。试试吧
foreach ($gotdata as $key1 => $value1) {
$address = "";
$product = "";
foreach ($value1 as $key2 => $value2) {
//print " key2: " . $key2 . " value2: ". $value2;
if($key2 == 'Address'){
$address = $value2;
print "address: ".$address; //able to get it on console
}
elseif($key2 == 'Product'){
$product = $value2;
print "product: ".$product; //able to get it on console
}
if($address!="" && $product!=""){
$shell = 'python /opt/getdata.py '.$address.' '.$product;
print "shell:" . $shell; //not able to get $address and $product
}
// $current = shell_exec($shell);
// $current = (int)$current;
// print "current:" . $current;
}
}
您还没有在代码中定义$ product。