xml foreach skipping over if statement in php - php

Here's what I am trying to achieve.
I am importing an xml file of products (the product tag has an id attribute:
as an example.
There is 1 tag (category) inside the product tag that I am trying to retrieve but I only want one instance of it. So I created a flag to help distinguish when the product id changes.
My code looks like this
<?php
$flag='start';
foreach($xml->product as $product)
{
$attrs = $product->attributes();
echo "$attrs ($flag)"; // just used for testing results
if ($flag != $attrs) {
echo "| <a href='xmltest.php?menuitem=$attrs'>".$product->category." </a><br>";
$flag=$attrs;
}
}
?>
What should happen on the first run is the flag doesn't match the attrs, the link is echoed, the flag now matches the attrs.
If I have 5 product tags with ID's of 1,1,2,2,2, the code should echo the link twice (first when $flag=start while $attrs=1, and when $flag=1 while $attrs=2)...
Instead, it echoes it all 5 times, basically ignoring the if statement.
I can't see where I am going wrong with the if statement. Can anyone help?
Update Thanks Showerhead, I have been trying your suggestions and I am a bit closer than before.
I did the var_dump and the result I am seeing looks like this
flag var_dump result:string(5) "start"
attrs var_dump result: object(SimpleXMLElement)#6 (1) { ["#attributes"]=> array(1) {
["id"]=> string(1) "0" } } 0 (0)
flag var_dump result:object(SimpleXMLElement)#6 (1) { ["#attributes"]=> array(1) {
["id"]=> string(1) "0" } }
attrs var_dump result: object(SimpleXMLElement)#5 (1) { ["#attributes"]=> array(1) {
["id"]=> string(1) "0" } } 0 (0)
flag var_dump result:object(SimpleXMLElement)#5 (1) { ["#attributes"]=> array(1) {
["id"]=> string(1) "0" } }
attrs var_dump result: object(SimpleXMLElement)#4 (1) { ["#attributes"]=> array(1) {
["id"]=> string(1) "0" } } 1 (0)
flag var_dump result:object(SimpleXMLElement)#4 (1) { ["#attributes"]=> array(1) {
["id"]=> string(1) "0" } }
attrs var_dump result: object(SimpleXMLElement)#8 (1) { ["#attributes"]=> array(1) {
["id"]=> string(1) "1" } } 1 (1)
flag var_dump result:object(SimpleXMLElement)#8 (1) { ["#attributes"]=> array(1) {
["id"]=> string(1) "1" } }
I understand now how the $flag var starts off as a string and then adopts the value of the array.
I tried if( ! is_array($flag) && $flag != $attrs) { but the results were the same.
Is there another way I can get the values to be similar for comparison?
Thanks again,
UPDATE
a simple explode helped solve it. Here is the code that is working for me.
<?php
$flag='start';
foreach($xml->product as $product)
{
$category = $product->category;
$attrsvar = $product->attributes();
$attrs = explode(" ", $attrsvar);
if( ! is_array($flag) && $flag != $attrs[0]) {
echo " <a href='xmltest.php?menuitem=".$attrs[0]."'>".$category." </a> | ";
$flag=$attrs[0];
}
}
?>

You are going to want to make sure it is not an array first.
if( ! is_array($flag) && $flag != $attrs) { etc... }
There that should be it, sorry if you were reading first post before I edited it. I completely misread your problem. Now the reason this should work is because you were originally trying to compare an array to a string, which was probably throwing silent errors.
Edit: If its still not working try var_dump() to make sure both variables are the same type when they are being compared.
Update: You know what, we are both over thinking this. I will assume you are doing something with this XML other than just getting categories, otherwise you can look into the much simpler XPATH solution below. If you are doing something more with this XML you could just do the following.
$products = array();
foreach($xml->product as $product) {
$id = $product['id'];
$category = $product->category;
if( ! in_array($id, $products)) {
$products[$id] = $category;
echo "| <a href='xmltest.php?menuitem=$attrs'>".$category." </a><br>";
}
}
XPATH for if you just want to work with categories. Let me know if my XPATH is not quite right, I'm not too good with it under normal circumstances, I'd hate to think how badly I could mangle it under sleep depravation.
$categories = $xml->xpath('//product/category');
$categories = array_unique($categories);
foreach($categories as $category) {
echo "| <a href='xmltest.php?menuitem=$attrs'>".$category." </a><br>";
}

Related

How to add data to OBJECT from Wordpress get_results in PHP

Seems really easy, but I can't seem to figure it out...
I have a simple line that gets mysql results through wordpress like this:
$sql_results = $wpdb->get_results($sql_phrase);
Then I parse it as JSON and echo it: json_encode($sql_results);
However, I want to add other data before I parse it as JSON. But I'm not sure how.
$sql_results basically gets me a list of post ID's, title and category.
It looks like this in var_dump (this is just the first row):
array(1)
{
[0]=> object(stdClass)#2737 (7)
{
["ID"]=> string(4) "2700"
["post_title"]=> string(18) "The compact helmet"
["category"]=> string(5) "Other"
}
}
Now to start with something easy, I'd like all associative arrays inside the object to have the extra key-value. I tried the following but got an error:
500 Internal error.
foreach($sql_search as $key => $value)
{
$value['pic_img'] = "test";
$sql_search[$key]=$value;
}
$result=$sql_search;
$sql_results = array(1)
{
[0]=> object(stdClass)#2737 (7)
{
["ID"]=> string(4) "2700"
["post_title"]=> string(18) "The compact helmet"
["category"]=> string(5) "Other"
}
}
foreach($sql_results as $key=>$value)
{
$value->solution = 'good';
$sql_results[$key]=$value;
}
$result=$sql_results;
var_dump($result);
$test = array ( array("ID"=>"35", "name"=>"Peter", "age"=>"43"),
array("ID"=>"34", "name"=>"James", "age"=>"19"), array("ID"=>"31", "name"=>"Joe", "age"=>"40") );
foreach($test as $key=>$value)
{
$value['solution'] = 'good';
$test[$key]=$value;
}
$result=$test;
var_dump($result);

array return wrong value laravel

I make an ajax request and the response its an array of images, the problem is that i echo the value of the array and its the one that i want, but when the foreach ends and i see what have the array every value its changed by the last item of the array
foreach ($x as $y) {
$auxImg->misc_id = $y->misc_id;
$auxImg->image = $y->image;
$aux[$i] = $auxImg;
echo $aux[$i]->image.' ';
//response of the array in the echo
/* 5/maqueta.png - 5/ponto.png - 5/ciades.jpg - 5/35235.jpg */
$i++;
}
echo var_dump($aux);
//response in the var_dump of the aux array
array(4) {
[0]=>
object(stdClass)#400 (2) {
["misc_id"]=>
int(9)
["image"]=>
string(11) "5/35235.jpg"
}
[1]=>
object(stdClass)#400 (2) {
["misc_id"]=>
int(9)
["image"]=>
string(11) "5/35235.jpg"
}
[2]=>
object(stdClass)#400 (2) {
["misc_id"]=>
int(9)
["image"]=>
string(11) "5/35235.jpg"
}
[3]=>
object(stdClass)#400 (2) {
["misc_id"]=>
int(9)
["image"]=>
string(11) "5/35235.jpg"
}
}
i really cant understand why this happend, that is the only time i use $aux var please help
The problem here is that $auxImg is all the time the same object, so in each step you modify this object and append it to array but because $auxImg is an object it's not copied.
You should add
$auxImg = new stdClass();
or
$auxImg = clone $auxImg;
(depending what code you use before loop)
after:
foreach ($x as $y) {
to get expected result.

Remove from multidimensional array if value partially matches

I write a multilingual wordpress homepage. I need to load all languages into array, then detect the user language and then depending on user language remove the other languages from the array.
I want to do partial check on array to see if "Title" contains _DE or _ES and then depending on result remove one or the other from array.
So far I have
Data
array(2) {
[1]=> array(3) { ["order"]=> string(1) "1" ["title"]=> string(9) "Slider_ES" ["id"]=> string(3) "500" }
[2]=> array(3) { ["order"]=> string(1) "2" ["title"]=> string(11) "Slider_DE" ["id"]=> string(3) "493" }
}
Logic
$current_language = get_locale(); // Wordpress function which returns either es_ES or de_DE codes
if ($current_language == es-ES) {
foreach ($array as $key => $item) {
if ($item['title'] === '_DE') {
unset($array[$key]);
}
}
} else {
foreach ($array as $key => $item) {
if ($item['title'] === '_ES') {
unset($array[$key]);
}
}
}
What did I miss?
You can use the strpos function which is used to find the occurrence of one string inside other like this:
if (strpos($item['title'],'_DE') !== false) {
unset($array[$key]);
}

How to edit mulltidimensional array elements in php?

this is my array:
$array= array(3) {
[0]=> array(3) { ["name"]=> "one" ["com"]=> "com1" ["id"]=> "1" }
[1]=> array(3) { ["name"]=> "two" ["com"]=> "com2" ["id"]=> "2" }
[2]=> array(3) { ["name"]=> "three" ["com"]=> "com3" ["id"]=> "3" }
I need posibility to change values of name and com for specific id. I try some examples from Stack questions:
1.Link1
foreach($array as &$value){
if($value['id'] == 1){
$value['name'] = 'test';
$value['com'] = 'test';
break; // Stop the loop after we've found the item
}
}
But it don't work. no error but no result too.
2.Link 2
Again,no error message,but no result...
I also try a lot of other examples from Stack but fake,and finaly to write a question..
Buy,
P
Since you are not changing your array value that's why it's-not giving you desired output. Try this:-
foreach($array as $key => &$value){
if($key == 1){
$array[1]['name'] = 'test';// change value to original array
$array[1]['com'] = 'test'; //change value to original array
break; // Stop the loop after we've found the item
}
}
for($i=0;$i<count($array);$i++) {
if($array[$i]['id'] == 1) {
$array[$i]['name'] = 'test';
$array[$i]['com'] = '';
break;
}
}
print_r($array);
If you are able to change the array on creation I would recommend shifting the id to the array's key identifier. Would make life a lot easier to just do:
$array[1]['name'] = 'test';
Otherwise use the for loop posted above and look it up. (Right awnser)

PHP foreach loop through array

I have a fairly big array that I source from Facebook:
array(25) {
[0]=>
array(14) {
["id"]=>
string(31) "245226895508982_651884328176568"
["from"]=>
array(2) {
["name"]=>
string(16) "Madeleine Björs"
["id"]=>
string(15) "100002249777453"
}
["to"]=>
array(1) {
["data"]=>
array(1) {
[0]=>
array(2) {
["name"]=>
string(31) "Wohnung/WG in München gesucht!"
["id"]=>
string(15) "245226895508982"
}
}
}
Now what I want to do is go through the array and save ID, name and various other information from that array into a mysql database. However, to understand how to target specific information I tried to echo the data first.
$data = json_decode(file_get_contents('https://graph.facebook.com/'), true);
foreach($data as $item) {
echo $item['id'];
echo '<pre>'; var_dump($item);
}
This PHP code is based on various posts on Stackoverflow, however, the code returns nothing. May you please help me to target the arrays appropriately? You may check the enire array here: http://faculty-fight.de/milliondollaridea/facebook_session.php
Cheers!
foreach($array as $key=>$subArray)
{
foreach($subArray as $subKey=>subSubArray)
{
if(is_array($subSubArray))
{
foreach($subSubArray as $subSubKey=>$value)
{
if(is_array($value))
{
foreach($value as $valueKey=>$subValue)
{
/* your code /*
}
}
}
}
}
you can check for id values for example for 1st loop (if($subKey == "to")).

Categories