In PHP Trying to Get Array Foreach into XML - php

I Have an Array that I want a foreach to display the Key and Value as XML. The Page is coming up with <$value> and that is it? Any Ideas? Thank You!
$XML_a = array ("Ticket_ID" => "12343456");
$query = "";
$string_top =
"<varcor_api>
<response>";
foreach ($XML_a as $key => $value) {
$query .= "<" . $key . "><" . $value . "></" . $key . ">";
}
$string_bottom = "
</response>
</varcor_api>
";
echo $string_top . $query . $string_bottom;

It's bad idea to concatenate XML strings into XML structure. Instead, use Array to XML conversion algorithm - see Convert array to XML and How to convert array to SimpleXML.

Related

implode and show with key - php

I have an array with just a single element. The key and value looks like this:
Array ( [test] => 12342 )
Result i want is this inside an variable:
test = '12342'
I tried following:
$test = "'" . implode(" ", $metric) . "'";
print_r($test);
But this gives only gives me: '12342', i wanted the '=' after key and '' around the value (this is used for SQL later on). So the result should be test = '12342'. Does not look like implode would work here. I tried looking at http_query_builder but failed.
If this array is only ever going to contain one single item, then you don’t need to loop through the data, but you can use key and current instead:
$data = ['test' => 12342];
echo key($data) . " = '" . current($data) . "'";
key gets you the key of the “current” item, and current gets its value.
By just replying your question as it is using that unique example you would do it this way assuming there is only 1 value inside your array :
$yourArray = array('test' => '12342');
foreach($yourArray as $key => $value) {
$test = $key . " = '" . $value . "'";
}
print_r($test);
If there are multiple you would do this, as each key is unique :
$yourArray = array('test' => '12342', 'testing' => '24321');
$test = array();
foreach($yourArray as $key => $value) {
$test[$key] = $key . " = '" . $value . "'";
}
var_dump($test);

PHP: Creating an associative array programmatically

I have a return string from a 3rd party plugin that looks like a var_dump from an array. I'm trying to parse into a valid associative array. Looking at various examples and doing some tests with the code that follows. The last segment demonstrates the problem I'm having. I'm trying to parse out the data into a string and then programmatically create an array after my data string has been finished. When I do a print_r on $vegetables2, I get:
Array([0] => “Gourd”=”40 kilojoules”,”Artichoke”=”105 kilojoules”,”Cassava”=”550 kilojoules”)
And the echo $vegetables2["Artichoke"] produces no value. Can someone please guide me at the correct syntax to create the array equivalent to the first two examples?
//this works:
echo "From creating the entire array with a static string:<br/>";
$vegetables = array("Gourd"=>"40 kilojoules", "Artichoke"=>"105 kilojoules", "Cassava"=>"550 kilojoules");
echo "Artichoke: " . $vegetables["Artichoke"] . "<br/>";
//this works too
$vegetables1['Gourd'] = "40 kilojoules";
$vegetables1['Artichoke'] = "105 kilojoules";
$vegetables1['Cassava'] = "550 kilojoules";
echo "From creating one element at a time:<br/>";
echo "Artichoke: " . $vegetables1["Artichoke"] . "<br/>";
//this doesn't work
$strData = "\"Gourd\"=\"40 kilojoules\",";
$strData = $strData . "\"Artichoke\"=\"105 kilojoules\",";
$strData = $strData . "\"Cassava\"=\"550 kilojoules\"";
echo $strData ."<br/>";
$vegetables2 = array($strData);
print_r($vegetables2);
echo "Artichoke: " . $vegetables2["Artichoke"];
$strData = "\"Gourd\"=\"40 kilojoules\",";
$strData = $strData . "\"Artichoke\"=\"105 kilojoules\",";
$strData = $strData . "\"Cassava\"=\"550 kilojoules\"";
$dd=str_replace('"','',"$strData");
$ff=explode(',',$dd);
foreach ($ff as $c)
{
$xx=explode('=',$c);
$vegetables2["$xx[0]"]=$xx[1];
}
print_r($vegetables2);
echo "Artichoke: " . $vegetables2["Artichoke"];
This string is your input:
"Array ( [Gourd] => 40 kilojoules [Artichoke] => 105 kilojoules [Casava] => 550 kilojoules )"
use strpos() to locate "("
use strpos() to locate ")"
use substr() to get what is between ( and )
use explode to divide the result wherever "[" appears
use array() to start a new array
use foreach to reformat each piece
use explode to divide each piece wherever "=>" appears
use trim to remove excess characters (left and right)
use $data[$key] = $value to create a new array to your liking

Issue with Array and foreach

Hi I have this array called $allextensionsforque. See print_r below.
Array ( [0] => Local/101#from-queue/n,0 [data] => Local/101#from-queue/n,0 )
I'm trying a foreach like below but its not showing any data on the echo. Can anyone help?
$allextensionsforqueu = mysqli_query($conqueue,"SELECT data FROM queues_details WHERE id = '1' AND keyword ='member'");
$allextensionsforque = mysqli_fetch_array($allextensionsforqueu);
$foo = "";
foreach ($allextensionsforque as $extensionrow)
{
$extensionrowstriped = substr($extensionrow['data'],6,3);
$foo = "' " . $extensionrowstriped . " ' ,";
}
echo $foo;
You don't have an array in $extensionrow, since it's only an one dimensional array. So you just need to replace $extensionrowstriped = substr($extensionrow['data'],6,3); with $extensionrowstriped = substr($extensionrow,6,3);.
Check for errors using mysqli_error(). Here is a simple approach, but you may want to improve it for production use:
$allextensionsforqueu = mysqli_query($conqueue,"...") or die(mysqli_error($conqueue));
Next, append your data to $foo instead of overwritting it in each loop:
$foo .= "' " . $extensionrowstriped . " ' ,";
Finally, verify that $extensionrow contains the data that you expect. substr() will return false if a match is not found.

The word Array is displayed as the first item

I am getting the values from an array this is taken from jQuery.serialize() just an input field. I then send then form data to a sendMail page.
Display the results in an email and the word Array is the first word then the value inputted follows, the rest of the data displayed is ok.
I have four arrays and in front of each the word Array appears.
$qty = $_POST['qty'];
foreach($qty as $value)
{
$qty .= $value . "<br>";
}
$desc = $_POST['description'];
foreach($desc as $value)
{
$desc .= $value . "<br>";
}
$options = $_POST['options'];
foreach($options as $value)
{
$options .= $value . "<br>";
}
$price = $_POST['price'];
foreach($price as $value)
{
$price .= $value . "<br>";
}
input would be qty: 1, Desc: description, options: small, price: 1.99
output is Array 1, Array description, Array options, Array small.
only on the first line the rest of the lines are ok.
You are concatenating to the POST array you should do this instead:
$qty = $_POST['qty'];
foreach($qty as $value)
{
$qty2 .= $value . "<br>";
}
echo $qty2;
Each part of your code contain the inconsistency of both assuming you have an array as POST-data and then assigning it as an string.
$possible_array = $_POST['possible_array'];
foreach($possible_array as $value)
{
$possible_array .= $value . "<br>"; // < - here you use $possible_array as a string
}
One way forward should be to assign the string value to another string:
$possible_array = $_POST['possible_array'];
foreach($possible_array as $value)
{
$string .= $value . "<br>"; // < - change to a new string
}
However it seem not probable that you actually have POST-data in arrays here I guess you send different items which each have the properties qty, description etc
I think you would like to use a solution where you iterate (foreach) on product info as an two-dimensional array, like $_POST['products']['qty'] where products is an array. But to help you further you would need to include your POST-data to see how its structured/serialized.
That happens because you append the value of each array to the array itself. Due to the value being a string the result also becomes a string. So the array will implicitly be casted to a string which results in the word "Array".
Possible solution:
$qtyList = implode('<br>' , $_POST['qty']);

Frustration at trying to output two specific values from an Array

I am doing my head in trying to do a simple retrieval for specific arrays within a script so I have an original associative array:
$vNArray ['Brandon'] = $item[3];
$vNArray['Smith']= $item[4];
$vNArray ['Johnson']= $item[5];
$vNArray ['Murphy']= $item[6];
$vNArray ['Lepsky']= $item[7];
Which outputs a common result for most values:
foreach ($vNArray as $key => $value){
if(!empty($value)){
$result .= "\t\t\t\t<li><strong>$key</strong>" .$value. "</li>\n";
}
But then I want two of these arrays to render differently so I added another script suggested by someone:
$display_id=array('Brandon', 'Murphy');
foreach ($vNArray as $key => $value){
if(!empty($value)){
//Looks into the display_id array and renders it differently
if (in_array($key, $display_id)) {
$result .= "\t\t\t\t<li id=\"$key\"><strong>$key</strong>$value</li>\n";
} else {
$result .= "\t\t\t\t<li><strong>$key</strong>$value</li>\n";
}
}
}
The problem is that i want the result for these arrays to contain both within the first result but when I tried to output
$result .= "\t\t\t\t$key[1]".$value[1]." \n";
PHP thinks that the index is the value's character index, so I'm having major syntax issues like id="/" r.
I have also tried
$result .= "\t\t\t\t<li id=\"". $display_id['Brandon']$value.\""><strong>$key[1]</strong>". $display_id['Murphy']$value." </li>\n";
But I am still getting wrong syntax issues...like
syntax error, unexpected T_VARIABLE
Or some other error like this.
Could someone please help?
EDITED
I have made the syntax corrections but I still need to specify the index:
The result from
result .= "\t\t\t\t<li id=\"". $display_id['Brandon'] . $value."\"><strong>" . $key[1] . "</strong>". $display_id['Murphy'] . $value." </li>\n";
Needs to be (Note how each value is on the same output depending on what I'm targeting):
<li id="Brandon Value"><strong>Brandon</strong> Murphy Value</li>
Right now it ignores the index value of . $display_id['Brandon'] . $value. or . $display_id['Murphy'] . $value." all together and just repeats:
<li id="Brandon Value"><strong>Brandon</strong> Brandon Value</li>
<li id="Murphy Value"><strong>Murphy</strong> Murphy Value</li>
Just do $key, forget the [1] bit. Same with $value.
Each value needs to be concatenated with another, so for example:
echo $a . $b . $c . $d . $e;
Notice the . contact that joins each variable with the the next / prev variable, so your line:
$display_id['Brandon']$value
should look like:
$display_id['Brandon'] . $value
^
I would do the following though.
$result .= sprintf('<li id="%s"><strong>%s</strong> %s</li>',$display_id['Brandon'] . $value,$key[1],$display_id['Murphy'] . $value);
Also using sprintf also make your code more readable.

Categories