Get the specific identifier in xml code with php - php

Good day,
I'm trying to get a specific value of an XML file in this example I need to get a
productidentifier in each product that has the tag <b221> set to 03 something like this:
<productidentifier><b221>03</b221><b244>9783672461027</b244></productidentifier>
where I can get then the <b244> tag to store the EAN.
The problem is that specific items have sometimes more then one productidentifier for example:
<productidentifier><b221>02</b221><b244>3672461024</b244></productidentifier>
<productidentifier><b221>03</b221><b244>9783672461027</b244></productidentifier>
So far I tried to use:
foreach ($xml->product as $item) {
$item->productidentifier->b221
}
Which will always return me the first productidenfitier in the list
foreach ($xml->product as $item) {
$identifier = $item->productidentifier->xpath('//productidentifier');
dd($identifier);
}
Which returns me all the product identifiers in the list:
https://i.stack.imgur.com/mq0NE.png
How to do it?
Thank you for reading.

You would need to extend your XPath expression to include a check that the <b221> element is 03. This code searches for these and outputs the <b244> value
foreach ( $xml->xpath('//productidentifier[b221="03"]') as $product ) {
echo $product->b244.PHP_EOL;
}

Related

PHP: Append array in foreach loop with elements on condition with matching elementId

I have an array with with different code numbers, and in turn each code can refer to different items. However, every code can refer to many items, while every item can have many codes (i.e. many-to-many relation between codes and items).
I have the items and I have the item codes, and now I want to append the right codes to the right items via a loop in a code snippet looking this (each $itemCode object includes an $item.Id property):
foreach($itemCodes as $itemCode) {
$itemCodesForItem = [];
foreach($items as $item) {
if($itemCode->getItem()->getId() == $item->getId()) {
array_push($itemCodesForItem, $itemCode->getCode());
$item->setCode($itemCodesForItem); // Assign with array with all appended codes for a specific item
}
}
}
The issue here is that every matching code overwrites the previous matching one, so in the end it only assigns one code to each item. But if an item has several codes, I want all those codes appended in the array for the specific item, and not only the last matching one. Does anyone know how to catch and append the right codes to the right items here?
Ok, so finally I got it working with the following code:
foreach($items as $item) {
$itemCodesForItem = [];
foreach($itemCodes as $itemCode) {
while($itemCode->getItem()->getId() == $item->getId()) {
array_push($itemCodesForItem, $itemCode->getCode());
$item->setCode($itemCodesForItem);
break;
}
}
}

How to get each value in a column of database in php

I don't have enough knowledge about this criteria:
I want to loop inside the for each loop to get all values in a particular column.
For example: I got the values from DB through get_result and store the result in $results.
After that use:
for each($results as $result)
❴
$output = $result->message
❵
Where message is a column in DB.
I want to loop over all the messages instead of storing last one by replacing.
Can you please give me suggestions on how to loop inside for each?
Try this:
$output[] = $result ->message;
Now $output will contain all messages on index 0, 1, 2 ...
You are facing the issue because:
$output=$result ->message;
the above line is present inside the loop, and each new iteration onerride the old value.
Well if you just looking for foreach inside foreach then you can try the following.
<?php
foreach($results as $result){
$output=$result->message;
foreach($output as $messages){
echo $messages;
}
}
?>
You don't need to put the message into another variable. You can do whatever you need to do inside the loop. For example, if you are displaying the messages, you can get it done inside the loop:
foreach ($results AS $result) {
echo $results->message . "<br>";
}

Assign foreach variables

I've tried, believe me I've tried to figure this out but for the best part of the day it has beaten me so I have to ask this question:
I have a list ($list) of 100 words which I have put into an array:
foreach ($tag_array as $key => $names ) {
Each of these names I want to be a variable which I can use to assign some html for output within a html eg:
$arrayitem6 = 'whatever';
print $arrayitem6;
The reason I want to do this is because the 100 items in the list actually turns into 400 items in a html page which I would have to manually write out into a huge long repeating block of html. I want to create a single block of html/code using the array list and foreach.
I hope I've made myself understood. I'm sure it's a straight forward bit of coding but as a novice I cannot fathom.
thanks in advance for any help
I have searched the internet and googled but I can't locate an answer. I'll keep looking.
thanks
Try following
<?php
foreach ($tag_array as $key => $names ) {
${"arrayitem$key"} = $names;
}
echo $arrayitem0;
?>
You can access variable as $arrayitem0, $arrayitem0 and so on depending upon key ($key) of your $tag_array
I think this is what you are looking for.
<?php
foreach ($tag_array as $key => $names ) {
$."arrayitem".$key = $names;
}
echo $arrayitem6;
?>
you can access variable as $arrayitem0 ,$arrayitem1...till 99

Accounting for missing array keys, within PHP foreach loop

I'm parsing a document for several different values, with PHP and Xpath. I'm throwing the results/matches of my Xpath queries into an array. So for example, I build my $prices array like this:
$prices = array();
$result = $xpath->query("//div[#class='the-price']");
foreach ($result as $object) {
$prices[] = $object->nodeValue; }
Once I have my array built, I loop through and throw the values into some HTML like this:
$i = 0;
foreach ($links as $link) {
echo <<<EOF
<div class="the-product">
<div class="the-name"><a title="{$names[$i]}" href="{$link}" target="blank">{$names[$i]}</a></div>
<br />
<div class="the-image"><a title="{$names[$i]}" href="{$link}" target="blank"><img src="{$images[$i]}" /></a></div>
<br />
<div class="the-current-price">Price is: <br> {$prices[$i]}</div>
</div>
EOF;
$i++; }
The problem is, some items in the original document that I'm parsing don't have a price, as in, they don't even contain <div class='the-price'>, so my Xpath isn't finding a value, and isn't inserting a value into the $prices array. I end up returning 20 products, and an array which contains only 17 keys/values, leading to Notice: Undefined offset errors all over the place.
So my question is, how can I account for items that are missing key values and throwing off my arrays? Can I insert dummy values into the array for these items? I've tried as many different solutions as I can think of. Mainly, IF statements within my foreach loops, but nothing seems to work.
Thank you
I suggest you look for an element inside your html which is always present in your "price"-loop. After you find this object you start looking for the "price" element, if there is none, you insert an empty string, etc. into your array.
Instead of directly looking for the the-price elements, look for the containing the-product. Loop on those, then do a subquery using those nodes as the starting context. That way you get all of the the-product nodes, plus the prices for those that have them.
e.g.
$products = array();
$products = $xpath->query("//div[#class='the-product']");
$found = 0 ;
foreach ($products as $product) {
$products[$found] = array();
$price = $xpath->query("//div[#class='the-price']", $product);
if ($price->length > 0) {
$products[$found] = $price->item(0)->nodeValue;
}
$found++;
}
If you don't want to show the products that don't have a price attached to them you could check if $prices[$i] is set first.
foreach($links AS $link){
if(isset($prices[$i])){
// echo content
}
}
Or if you wanted to fill it will dummy values you could say
$prices = array_merge($prices,
array_fill(count($prices), count($links)-count($prices),0));
And that would insert 0 as a dummy value for any remaining values. array_fill starts off by taking the first index of the array (so we start one after the amount of keys in $prices), then how many we need to fill, so we subtract how many are in $prices from how many are in $links, then we fill it with the dummy value 0.
Alternatively you could use the same logic in the first example and just apply that by saying:
echo isset($prices[$i]) ? $prices[$i] : '0';
Hard to understand the relation between $links and $prices with the code shown. Since you are building the $prices array without any relation to the $links array, I don't see how you would do this.
Is $links also built via xpath? If so, is 'the-price' div always nested within the DOM element used to populate $links?
If it is you could nest your xpath query to find the price within the query used to find the links and use a counter to match the two.
i.e.
$links_result = $xpath->query('path-to-link')
$i = 0
foreach ($links_result as $link_object) {
$links[$i] = $link_object->nodeValue;
// pass $link_object as context reference to xpath query looking for price
$price_result = $xpath->query('path-to-price-within-link-node', $link_object);
if (false !== $price_result) {
$prices[$i] = $price_result->nodeValue;
} else {
$prices[$i] = 0; // or whatever value you want to show to indicate that no price was available.
}
$i++;
}
Obviously, there could be additional handling in there to verify that only one price value exists per link node and so forth, but that is basic idea.

adding an element to multidimensional array when within foreach loop (PHP)

I'm trying to check if a certain category is allready selected by looping through an array of categories also I want to add another element to the array whci is just a bit to indicate is the category selcated
my categories array looks like this
0=>array(category_id=>12,category_name=>"blogger")
1=>array(category_id=>13,category_name=>"dancer")
etc...
now the code i'm trying goes like that:
foreach ($userCategories as $key=>$category) {
if($category['category_id'] == $mediaDetails['currentCategory']) {
$category['current'] = 1;
} else {
$category['current'] = 0;
}
}
when executing
die(var_dump($userCategories));
I expect to get an array similar to
0=>array(category_id=>12,category_name=>"blogger",current=>0)
1=>array(category_id=>13,category_name=>"dancer",current=>1)
but instead I get the same array I had before the foreach loop
any ideas?
Thanks
It looks like $category is not getting passed by reference.
Try $userCategories[$key]['current']=1 instead, and see how that works.

Categories