PHP variables, what is wrong with my code? - php

There is a PHP script that get's new data using python script.
I'm able to foreach and loop and get key2, and value2 for array but unable to get $address and $product variables to put it into $shell command. What is wrong with my variables?
Just starting to code, it would be helpful if anyone teaches me this.
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;
}
}
This is what the multidimensional array looks like.
The main array is different size every time I run the script. It could be 10 or 14 etc.
The
subarrays on the other hand always have the same six items.
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"
}

I assume you can access the values you want directly from the main loop.
EDIT: Now that the array has been posted, I'm sure this will work.
No need to nest loop the array
foreach ($gotdata as $key1 => $value1) {
$shell = 'python /opt/getdata.py '.$value1['Address'] . ' ' . $value1['Product'];
print "shell:" . $shell; //not able to get $address and $product
}
Nesting a foreach loop is the same as accessing the subarray item.

i do not know what is your desire output. But if you want both values. Try it
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;
}
}
Also you have not define $product in your code.

Related

Find duplicate elements in an array

I got an array of coins with many details, that looks partially like that:
array(360) {
["VEN/USDT"]=>
array(15) {
["tierBased"]=>
bool(false)
}
["id"]=>
string(7) "VENUSDT"
["symbol"]=>
string(8) "VEN/USDT"
["base"]=>
string(3) "VEN"
["quote"]=>
string(4) "USDT"
["lot"]=>
float(0.01)
["active"]=>
bool(true)
}
All I need is this part:
["id"]=>
string(7) "VENUSDT"
["symbol"]=>
string(8) "VEN/USDT"
["base"]=>
string(3) "VEN"
["quote"]=>
string(4) "USDT"
if "base" is more often than once in the entire array.
The final code was:
$base_array = array();
foreach ($markets as $key=>$value) {
echo "1. Key = " . $key . "\n";
foreach ($value as $key => $value) {
if ($key == "base") {
echo "Base = " . $value . "\n";
array_push($base_array, $value);
}
}
}
// Duplicates we need only!
$unique = array_unique($base_array);
$duplicates1 = array_diff_assoc($base_array, $unique);
$duplicates = array_unique($duplicates1);
var_dump($duplicates);

How to loop and get serialized values from database with php

I'm developing a pizza's restaurant ecommerce and now I'm trying to get the size (Familiar) and the ingredients (Pernil dol�, Bac�, Emmental) of a pizza that was ordered previously. The data I want to get (the italic values in this paragraph) becomes serialized from database:
a:4:{s:10:"attributes";a:2:{s:6:"Tamany";a:1:{i:3;s:8:"Familiar";}s:11:"Ingredients";a:3:{i:318;s:12:"Pernil dol�";i:270;s:5:"Bac�";i:294;s:8:"Emmental";}}s:9:"shippable";s:1:"0";s:4:"type";s:5:"pizza";s:6:"module";s:10:"uc_product";}array(4) { ["attributes"]=> array(2) { ["Tamany"]=> array(1) { [3]=> string(8) "Familiar" } ["Ingredients"]=> array(3) { [318]=> string(11) "Pernil dol�" [270]=> string(4) "Bac�" [294]=> string(8) "Emmental" } } ["shippable"]=> string(1) "0" ["type"]=> string(5) "pizza" ["module"]=> string(10) "uc_product" }
I discovered 'unserialized' php method and I tried this:
$attr = $row['data']; // data from database
$data = preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $attr); // I did this because I get some errors...
After I did that, I got this multidimensional array (a bit more human readable):
array(4) { ["attributes"]=> array(2) { ["Tamany"]=> array(1) { [3]=> string(8) "Familiar" } ["Ingredients"]=> array(3) { [318]=> string(11) "Pernil dol�" [270]=> string(4) "Bac�" [294]=> string(8) "Emmental" } } ["shippable"]=> string(1) "0" ["type"]=> string(5) "pizza" ["module"]=> string(10) "uc_product" }
Next step was try to loop the resulting data with a foreach loop, like the following:
foreach($data['attributes'] as $item)
{
print '<ul>';
foreach($item as $value)
{
print_r('<li>' . $value . '</li>');
}
print '</ul>';
}
I'm a php beginner PHP developer and I can't figure out how can I loop this array in order to get the values I need. I'm getting this error:
Warning: Invalid argument supplied for foreach() in /home/my_host/public_html/dev.mysite.com/inc/file.php on line 79
Can anybody tell me how I have to loop this array to get the data?
Any help will be very, very appreciated.
Best regards,
I created this example for you. First I declared an array which believe mimics the array you have to parse. Then I looped through and outputed the contents of the array.
<?php
$array = array(
0 => array(
'0' => 'John Doe',
'1' => 'john#example.com'
),
1 => array(
'0' => 'Jane Doe',
'1' => 'jane#example.com'
),
);
foreach ($array as $key => $value) {
$thisArray = $array[$key];
print_r('<ul>');
foreach ($thisArray as $key2 => $value){
print_r('<li>'.$thisArray[$key2].'</li>');
}
print_r('</ul>');
}
?>
Finally, and based on the answer of #Gregory Hart, I reached my goal. This is the final code that makes it possible in my particular case:
$data = $row['data'];
$attrib = preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $data);
$attr = unserialize($attrib);
foreach ($attr as $key => $value)
{
print_r('<ul>');
$thisArray = $attr[$key];
foreach ($thisArray as $key2 => $value2)
{
print_r('<li>' . $key2 . ': ');
$thisArray2 = $attr[$key][$key2];
foreach ($thisArray2 as $key3 => $value3)
{
if ($key2 == 'Tamany')
print_r('<span class="label label-warning">' . utf8_encode($thisArray2[$key3]) . '</span> ');
if ($key2 == 'Ingredients')
print_r('<span class="label label-success">' . utf8_encode($thisArray2[$key3]) . '</span> ');
if ($key2 == 'Salsa')
print_r('<span class="label label-primary">' . utf8_encode($thisArray2[$key3]) . '</span> ');
}
print '</li>';
}
print_r('</ul>');
}
Thanks for you help!
Try this logic:
$data_unserialize = unserialize($row->data);
foreach ($data_unserialize as $data_key => $data_value) {
if($data_key =='size')
{
$thisArray = $data_unserialize[$data_key ];
foreach ($thisArray as $key2 => $value2){
if($key2=='attributes')
{
switch ($value2)
{
case "Pernil dol�":
echo'Pernil dol �';
break;
case "Emmental":
echo'Emmental';
break;
default:
echo 'Nothing';
}
}
}
}
}
NB:- And remove the break; from switch statement to display all ingrediants.

How to use foreach() to display results from array

I have the following query:
$sth = $this->db->prepare("SELECT * FROM comment WHERE status = 1");
$sth->setFetchMode(PDO::FETCH_ASSOC);
$sth->execute();
$reviews = array();
while($row = $sth->fetch()){
$reviews[]['name'] = $row['name'];
$reviews[]['comment'] = $row['comment'];
$reviews[]['star'] = $row['star'];
}
return $reviews;
}
Which returns the following for var_dump($this->reviews):
array(9) {
[0]=> array(1) { ["name"]=> string(5) "name1" }
[1]=> array(1) { ["comment"]=> string(8) "comment1" }
[2]=> array(1) { ["star"]=> string(1) "4" }
[3]=> array(1) { ["name"]=> string(5) "name2" }
[4]=> array(1) { ["comment"]=> string(8) "comment2" }
[5]=> array(1) { ["star"]=> string(1) "4" }
[6]=> array(1) { ["name"]=> string(5) "name3" }
[7]=> array(1) { ["comment"]=> string(8) "comment3" }
[8]=> array(1) { ["star"]=> string(1) "4" }
}
How can I use foreach to display name, comment, star by row?
I.e.:
name1, email1#email.com, comment1
name2, email2#email.com, comment2
name3, email3#email.com, comment3
I know it should be something like:
foreach( $this->reviews as $key){
echo "Name:". $this->reviews['name'] . "Email:" . $this->reviews['email'] . "Comment:" . $this->reviews['comment'];
}
But this gives me Notice: Undefined index: name. How do I define the index?
You are setting up the insert into the array incorrectly:
while($row = $sth->fetch()){
$reviews[]['name'] = $row['name'];
$reviews[]['comment'] = $row['comment'];
$reviews[]['star'] = $row['star'];
}
The shorthand [] inserts a new element each and every single time, you want to actually insert an array AS the element.
while($row = $sth->fetch()){
$revArr=array('name' => $row['name'], 'comment' => $row['comment'], 'star' => $row['star']);
$reviews[]=$revArr;
}
Edit: Now change your second foreach to this:
foreach( $this->reviews as $key){
echo "Name:". $key['name'] . "Email:" . $key['email'] . "Comment:" . $key['comment'];
}
You need to generate an array of arrays. Something like
while($row = $sth->fetch()){
$reviews[] = array('name' => $row['name'], 'comment' => $row['comment'], 'star'=> $row['star']);
}
Now your $reviews object will have just as many elements as there were rows in the query result, and you can print it any way you want.
As for printing (which I think is where your error message is coming from):
foreach($reviews as $thisValue) {
echo "Name: ". $value['name'];
}
should work.
You should use your foreach loop like this:
foreach( $this->reviews as $value){
echo "Name:". $value['name'] . "Email:" . $value['email'] . "Comment:" . $value['comment'];
}
Notice how i use $value instead of $this->reviews inside the loop.
foreach( $this->reviews as $key){
echo "Name:". $this->reviews['name'] . "Email:" . $this->reviews['email'] . "Comment:" . $this->reviews['comment'];
}
this is not the right way, because now you are working on $key so write -
foreach( $this->reviews as $key){
echo "Name:". $key['name'] . "Email:" . $key['email'] . "Comment:" . $key['comment'];
}
you can do it as follow:
$reviews = array();
while($row = $sth->fetch()){
$reviews[] = array($row['name'], $row['comment'], $row['email'], $row['star']);
}
and then you can do a heredoc:
$str = '';
foreach( $this->reviews as $review ){
$str .=<<<html
name: {$review['name']}
email: {$review['email']}
comment: {$review['comment']}
start: {$review['star']}
html;
}
finally i echo everything:
echo $str;
I think this is much cleaner, and you can add any html.

How the get line by line keys and values of one level JSON in PHP

I am receiving a JSON array from Javascript as a $_POST variable.
I want to get all variables and its values of the JSON. I tried to use json_decode with foreach like bellow but it did not work. my php code is
<?php
$string = $_POST['json'];
var_dump(json_decode($string, true));
foreach($string as $key => $value) {
echo $key . " : " . $value;
}
?>
my json is
[{"EXTAPP_ID":"9901","CATEGORY_ID":"10","LANGUAGE_CODE":"tr","CATEGORY_LANG_DESC":"TR AAA"},{"EXTAPP_ID":"9901","CATEGORY_ID":"10","LANGUAGE_CODE":"de","CATEGORY_LANG_DESC":"DE AAA"},{"EXTAPP_ID":"9901","CATEGORY_ID":"20","LANGUAGE_CODE":"de","CATEGORY_LANG_DESC":"DE XXX"},{"EXTAPP_ID":"9901","CATEGORY_ID":"20","LANGUAGE_CODE":"tr","CATEGORY_LANG_DESC":"TR YYY"},{"EXTAPP_ID":"9901","CATEGORY_ID":"10","LANGUAGE_CODE":"en","CATEGORY_LANG_DESC":"EN ZZZ"},{"EXTAPP_ID":"9901","CATEGORY_ID":"20","LANGUAGE_CODE":"en","CATEGORY_LANG_DESC":"EN VVV"}]
it returns the request as a array like bellow (I did not paste all result)
array(6) {
[0]=>
array(4) {
["EXTAPP_ID"]=>
string(4) "9901"
["CATEGORY_ID"]=>
string(2) "10"
["LANGUAGE_CODE"]=>
string(2) "tr"
["CATEGORY_LANG_DESC"]=>
string(19) "TR XXX"
}
[1]=>
array(4) {
["EXTAPP_ID"]=>
string(4) "9901"
["CATEGORY_ID"]=>
string(2) "10"
["LANGUAGE_CODE"]=>
string(2) "de"
["CATEGORY_LANG_DESC"]=>
string(17) "TR YYY"
}
[2]=>
what I expected was
EXTAPP_ID: 9901
CATEGORY_ID:10
LANGUAGE_CODE:de
CATEGORY_LANG_DESC:DE AAA
Decode the string with $string = json_decode($_POST['json'], true);
You can get desired result by following code
$string = $_POST['json'];
$string = json_decode($string, true);
foreach($string as $value) {
foreach($value as $k=>$v) {
echo $k . " : " . $v .'<br/>';
}
echo '<hr>';
}
Try this instead:
$string = json_decode($_POST['json'], true);
foreach($string as $key => $value) {
echo $key . " : " . $value;
}
Try this:
$string = $_POST['json'];
$data = json_decode($string, true);
var_dump($data);
foreach($data as $key => $value) {
echo $key . " : " . $value;
}

PHP Echo array values loop (no data displayed)

I have an array ... Here is the structure / data:
array(1) {
[0]=> object(SimpleXMLElement)#1 (18)
{
["data_123"]=> object(SimpleXMLElement)#3 (29)
{
["field1"]=> string(7) "123"
["field2"]=> string(2) "10"
["field3"]=> string(19) "2013-03-05 17:00:00"
["field4"]=> string(19) "2013-03-05 18:00:00"
}
["data_234"]=> object(SimpleXMLElement)#4 (29)
{
["field1"]=> string(7) "234"
["field2"]=> string(2) "10"
["field3"]=> string(19) "2013-03-05 17:40:00"
["field4"]=> string(19) "2013-03-05 18:10:00"
}
}
}
I am trying to create a loop to display the data but nothing is showing up:
foreach ($result as $key => $list) {
echo "key.: " . $key . "\n";
echo "field1: " . $list['field1'] . "\n";
echo "field2: " . $list['field2'] . "\n";
}
It's just not returning any data.
I'm guessing that the loop might be wrong for this array structure?
How can I get the data echoed for this array?
$list is an array of objects so you need two loops and appropriate syntax. e.g.:
foreach($list as $objects) {
foreach($objects as $key => $obj) {
echo "key.: " . $key . "\n";
echo $obj->field1 . "\n";
echo $obj->field2 . "\n";
echo $obj->field3 . "\n";
echo $obj->field4 . "\n";
}
}

Categories