Php Dom brother/sister node - proper way [duplicate] - php

This question already has an answer here:
Getting the value of brother/sister node
(1 answer)
Closed 9 years ago.
So I was playing with domDocs in php and I was going through structure of many nodes. When the script finds APP_ID it was looking for, he then need to return his brother value, APP_USER.
I found no solution on here, only XPath and jQuery that I find 'avoiding' of how it meant to be used.
It's very simple
Before you call foreach, put one iterating variable e.g. $i which will then 'call' the brother's value.
$apps = $root->getElementByTagName( 'APP_ID' );
$i=0
foreach( $apps as $app ) {
if( $app->item(0)->nodeValue == CONSTANT-ID ) { // just condition
$user = $root->getElementsByTagName( "APP_USER" );
echo $user->item($i)->nodeValue;
// this $i means it returns brother's value
}
$i++;
}
what do you think?

Starting from $app, you can use parentNode to go up one level and then iterate over childNodes to find the sibling APP_USER:
if( $app->nodeValue == CONSTANT-ID ) { // just condition
foreach ($app->parentNode->childNodes as $child) {
if ($child->localName == 'APP_USER') {
echo $child->nodeValue;
}
}
}

Related

Laravel, how to delete key and value in an array of a specific position? [duplicate]

This question already has answers here:
PHP Remove elements from associative array
(9 answers)
Closed 5 years ago.
The title says it all. I want to delete the highlighted section in yellow as shown in picture below. And rest remain unchanged. What is the best way to do it? Is there a method that does't use foreach?
you can do this just with one foreach!
foreach ($data as $key => $subArr) {
unset($subArr['id']);
$data[$key] = $subArr;
}
You can use the following
$filteredArray = array_map(function($array) {
unset($array['id']);
return $array;
}, $dataArray);
Instead of doing foreach() loop on the array, You can go with array_search()
$results=array_search($unwantedValue,$array,true);
if($results !== false) {
unset($array[$result]);
}

Using PHP foreach How to get first item from DB then others [duplicate]

This question already has answers here:
PHP - Grab the first element using a foreach
(10 answers)
Closed 5 years ago.
how can I get first item from db by foreach
$posts = new Posts();
$post = $posts->feature_post($conn);
foreach($post as $feature) { ?>
my html code is different for 1st item. so I need to get 1st item then other item,
how I can do it?
thanks in advance.
To get the first item of an array, you can use the reset function
http://php.net/manual/fr/function.reset.php
<?php
$posts = new Posts();
$listPost = $posts->feature_post($conn);
$firstPost = reset($listPost);
...
Also if you want to know if you loop through the first element and if the keys of your arrays are 0,1,2,3 etc..
<?php
foreach($array as $key => $cell) {
if ($key === 0) {
// this is your first element
....
}
}
If the keys of your array are not numeric indexes but you don't intend to use them, you can obtain such array by using the array_values function

For each array modification [duplicate]

This question already has answers here:
Why can't I update data in an array with foreach loop? [duplicate]
(3 answers)
Closed 8 years ago.
I have this following code:
foreach ($animals as $animal) {
$animal = getOffSpring($animal);
}
Since I am setting $animal to a new string, will I be modifying the array as well please?
My run suggests that my array remains the same, but I want it to be modified with the new value. Is this the bug?
In other words, I want all the animals within my array to be modified to their offsprings
I think you are trying to do that.
When you take $animal variable and pass it to a function or modifie it inside foreach loop, you work with independent variable, that isn't linked to $animals array in any way ( if you don't link it yourself ), therefore all changes applied to it, don't result in modification of $animals array.
foreach ( $animals as $i => $animal )
{
$animals[ $i ] = getOffSpring( $animal );
}
As #AlecTMH mentioned in his comment, array_map is also a solution.
array_map( 'getOffSpring', $animals );
You can use a reference:
foreach ($animals as &$animal) {
$animal = getOffSpring($animal);
}
unset($animal);
The unset after the loop clears the reference. Otherwise you keep a reference to the last array element in $animal after the loop which will cause annoying problems if you forget about this and then use $animal later for something else.
Another option would be using the key to replace it:
foreach ($animals as $key => $animal) {
$animals[$key] = getOffSpring($animal);
}
You can use a reference to the value in the array
foreach ($animals as &$animal) {
$animal = getOffSpring($animal);
}

Check if an array contains another array with PHP [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Checking if an array contains all elements of another array
I have posted something like this to the Stackoverflow before, but the answers do not fully satisfy me. That's why I'm posting the question again, but changing the question all along.
Some people helped me to construct a function that checks if an array($GroupOfEight[$i]) that is an element of a multidimensional array($GroupOfEight) equals another array($stackArray), disregarding the number ordering in the arrays.
However, what I need to check is whether the mentioned array($stackArray) contains any another array($GroupOfEight[$i]) in the multidimensional array($GroupOfEight) or not, that means main array($stackArray) can consist more elements than subarrays($GroupOfEight[$i]).
Here is the one working code that I've gathered so far, but need to be modified to the version I want:
<?php
$GroupOfEight = array (
array(0,1,3,2,4,5,7,6),
array(4,5,6,7,15,12,13,14),
array(12,13,15,14,8,9,11,10),
array(2,6,14,10,3,7,15,11),
array(1,3,5,7,13,15,9,11),
array(0,4,12,8,1,5,13,9),
array(0,1,3,2,8,9,11,10)
);
$stackArray = array(0,4,12,1,9,8,5,13,9,2,5,2,10);
/*$stackArray gets value with POST Method by URL parameter.
This is just the example. As you see this array contains
$GroupOfEight[4], and also it contains many other numbers.*/
/* The function given below checks if $stackArray equals any
of the subarrays of $GroupOfEight. However, we want to check
if $stackArray caontains any of the subarrays of function.
If it does, function should return the index number, if it
doesnt it should return -1.*/
function searcheight($stackArray,$GroupOfEight){
for($i=0; $i<count($GroupOfEight);$i++){
$containsSearch = (count(array_intersect($stackArray,$GroupOfEight[$i])) == count($stackArray) && count(array_intersect($stackArray,$GroupOfEight[$i])) == count($GroupOfEight[$i]));
if($containsSearch){
return $i; //This specifies which index in GroupOfEight contains a matching array
}
}
return -1;
}
// Calling the function that is given above.
echo searcheight($stackArray,$GroupOfEight);
?>
Any logical ideas or solutions will kindly be much appreciated. Thanks.
This one is fast:
function contains_array($array){
foreach($array as $value){
if(is_array($value)) {
return true;
}
}
return false;
}
You can try
$GroupOfEight = array(
array(0,1,3,2,4,5,7,6),
array(4,5,6,7,15,12,13,14),
array(12,13,15,14,8,9,11,10),
array(2,6,14,10,3,7,15,11),
array(1,3,5,7,13,15,9,11),
array(0,4,12,8,1,5,13,9),
array(0,1,3,2,8,9,11,10));
$stackArray = array(0,4,12,1,9,8,5,13,9,2,5,2,10);
function searcheight($stackArray, $GroupOfEight) {
$list = array();
for($i = 0; $i < count($GroupOfEight); $i ++) {
$intercept = array_intersect($GroupOfEight[$i], $stackArray);
$len = count($intercept);
if ($len % 4 == 0) {
$list[$i] = $len;
}
}
arsort($list);
if (empty($list))
return - 1;
return key($list);
}
echo searcheight($stackArray, $GroupOfEight);
Output
5

Array to XML: Howto import HTML as object to DOMDocument? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to insert HTML to PHP DOMNode?
PHP and DOMDocument
I am trying to write a Class that converts an array to XML using DOMDocument - and on top of that imports HTML into the DOM document. Problem is that the HTML is not imported into the DOM document - it gets imported as a text string (for instance, HTML tags are shown as <p> instead of <p> in the source for the resulting XML document).
Update:
Code added directly to this Question as requested by Hakre. The code is a bit hacked but works - it would be interesting though to get rid of the extend from DomDocument as suggested by Hakre.
class xmlizer extends DomDocument {
function __construct() {
parent::__construct();
}
function node_create($arr, $items = null) {
if (is_null($items))
$items = $this->appendChild($this->createElement("items"));
// Loop the array values.
foreach($arr as $element => $value) {
// If Array has numeric keys, use "node - else use $element.
$element = is_numeric( $element ) ? "node" : $element;
// Create element, add $value unless $value is an array - and append to main object ($items).
$fragment = $this->createElement($element, (is_array($value) ? null : $value));
$items->appendChild($fragment);
// Iterate if $value is an array, .
if (is_array($value)) {
self::node_create($value, $fragment);
}
}
}
public function __toString() {
// html_entity_decode() added by Micha. Thanks.
return html_entity_decode($this->saveXML());
}
}
// Build test Array with HTML string (for testing purposes only).
for($i=0;$i<3;$i++) {
$j = $i+1;
$array['example'][] = array(
"id" => $j,
"title" => "Title $j",
"description" => "<p>Text <strong>string</strong> nr. $j with <em>some</em> <code>HTML code</code>.</p>",
);
}
// Test: Run the code.
header("Content-Type:text/xml");
$xml = new xmlizer();
$xml->node_create($array);
echo $xml;
PS: Please don't close the Question as I don't think this is a duplicate. Thanks.
Try html_entity_decode($value) on line 15 in the second code but why you want the HTML as HTML because then it would be interpreted as XML.
Update
Sorry the one above doesn't work and this doesn't work too:
$this
->createElement($element)
->createTextNode(is_array($value) ? null : $value ));
Finaly I tryed it my self:
I think this is the best solution: http://codepad.org/PpyewkVd

Categories