How to save pairs of data into an one array - php

I have XML file where I have name of currency and rate. I want to save those currencies and rate as pairs into an array, but it doesnt work, when I echo the array with foreach only last one appears.
Here's my code:
<?php
$xml = simplexml_load_file("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");
$array=array();
foreach ($xml->children() as $cubeMain) {
foreach ($cubeMain->children() as $cubeTime) {
echo "Kursid seisuga: " . $cubeTime['time'];
foreach ($cubeTime->children() as $cubeCurr) {
$currency=$cubeCurr['currency'];
$rate=$cubeCurr['rate'];
$array = array((string)$currency => $rate);
echo $currency . " " . $rate . "<br />";
}
}
}
foreach ($array as $currency => $rate){
echo "$currency: $rate\n";
}
?>

try
$array[(string)$currency] = $rate;
instead of
$array = array((string)$currency => $rate);

If you expect to have several currency + rate couples, you'll want an array that contains sub-items, each one being made of currency + rate.
Typically, you'll first initialize your array :
$array = array();
Then, for each currency, you'll add an item into that array :
$array[] = array((string)$currency => $rate);
With that, you'll have a long list, but not indexed by currency -- which might not be that useful.
You'll probably, instead, prefer going with this second solution :
$array[(string)$currency] = $rate;
With that, your array will have the currency as key -- which make it much easier to find your data back, later.
Going with the second solution, your array is indexed by currency.
Which means you can find the rate for a specific currency this way :
echo $array['EUR']; // if EUR is an exinsting currency
And loop over all data like this :
foreach ($array as $currency => $rate) {
echo "$currency : $rate <br />";
}

Related

calculate the sum of values based on the input and match

To calculate the sum of values based on the input and match it with names in an array
$input = '500';
$array1 = array("200" => 'jhon',"300" => 'puppy',"50" => 'liza',
"150" => 'rehana',"400" => 'samra',"100" => 'bolda',);
need answer like this output
jhon,puppy and bolda,rehana
This code creates an array $data that contains names and their respective values. It then uses a foreach loop to iterate through the array and subtract the value of each name from the input until the input becomes zero. The names of all the values that were subtracted from the input are stored in an array $names. Finally, if the array $names is not empty, the names are echoed using implode separated by "and". If the array is empty, it means no match was found and a message "No match found" is echoed.
So I'm going to go out on a guess here. (this sounds like cheating on homework lmao).
You need to output pairs of names where the two names add upto 500 (the input).
This probably wont be the most optimal solution, but it should be a solution that works?
$input = 500;
// using shorthand array formatting
$array1 = [
200 => 'jhon',
300 => 'puppy',
50 => 'liza',
150 => 'rehana',
400 => 'samra',
100 => 'bolda'
];
// create an array that holds names we have already processed.
$namesProcessed = [];
// loop over the names trying to find a compatible partner
foreach ($array1 as $points => $name) {
foreach ($array1 as $pointsPotentialPartner => $namePotentialPartner) {
// Don't partner with yourself...
if ($name == $namePotentialPartner) {
continue;
}
// Don't partner with someone that has already been processed.
if (in_array($namePotentialPartner, $namesProcessed)) {
continue;
}
// test if the two partners add up to the input
if ($input == ($points + $pointsPotentialPartner)) {
// if this is the first partner set, don't put in 'and'
if (count($namesProcessed) == 0) {
echo $name . ', ' . $namePotentialPartner;
} else {
echo ' and ' . $name . ', ' . $namePotentialPartner;
}
$namesProcessed[] = $name;
$namesProcessed[] = $namePotentialPartner;
}
}
}
Hope this helps.

POST Array through JSON foreach

The question:
I have this array coming through a POST field
{"name":"sample","email":"a#sample.co.uk","comments":"test"}
I want to split it apart and run it through an array, so the end result would be
name sample
email a#sample.co.uk
comments test
What I have tried is this:
$a = $_POST['rawRequest'];
$a = json_encode($a);
foreach ($a as $k => $v) {
echo "\$a[$k] => $v <br />";
}
But it doesn't do anything, however when I test it with this variable (over using the POST)
$a = array("name" => 1,"email" => 2,"sample" => 3);
It works as expected.
Trying to understand what is going on
It is obviously because what I am dealing with here is two different types of array. However after endless google'ing I can't find anywhere which explains the difference (of the arrays below basically). So +1 to an explination which makes my relatively newbie mind understand what is happening and why it is wrong
{"name"=>"sample","email"=>"a#sample.co.uk"=>"comments":"test"}
{"name":"sample","email":"a#sample.co.uk","comments":"test"}
$aa Isn't a array, is a JSON:
$a = $_POST['rawRequest'];
$aa = json_encode($a);
Thus, you can't use foreach in $aa.
If you want to decode a json string into an array instead of an object, use the 'Array' flag.
$array = json_decode($json_string, true);
Try as
$data = '{"name":"sample","email":"a#sample.co.uk","comments":"test"}';
$json = json_decode($data,true);
foreach($json as $key=>$val){
echo $key." - ".$val;
echo "<br />";
}
Check the output here
http://phpfiddle.org/main/code/ytn-kp0
You have done as
echo "\$a[$k] => $v <br />";
This would output as
$a[name] => sample
"$a" will be considered as string
You can do the way you are doing but you need to change the echo something as
echo $k ."=>" .$v. "<br />";
Since you are looping the array using foreach and $k will contain the key of the array and $v will be the value !!
I have Json decoded the encoded array and looped it through a foreach below with comments explaining what each part does.
/* The Json encoded array.*/
$json = '{"name":"sample","email":"a#sample.co.uk","comments":"test"}';
/* Decode the Json (back to a PHP array) */
$decode = json_decode($json, true);
/* Loop through the keys and values of the array */
foreach ($decode as $k => $v) {
$new_string .= $k . ' | ' . $v . '<br/>';
}
/* Show the result on the page */
echo $new_string;
The above code returns the following;
name | sample
email | a#sample.co.uk
comments | test
If you want to access the array values one by one you can also use the following code.
/* The Json encoded array.*/
$json = '{"name":"sample","email":"a#sample.co.uk","comments":"test"}';
/* Decode the Json (back to a PHP array) */
$decode = json_decode($json, true);
echo $decode['name'];//returns sample
echo $decode['email'];//returns a#sample.co.uk
echo $decode['comments'];//returns test

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']);

Duplicate array values not working with Simple HTML DOM

I'm working with Simple HTML DOM like this:
foreach($html->find('img', 18) as $d) {
echo $d->outertext;
}
Now I want to implement an array of variables, in this case images, so I did:
$img=array(
"img"=>"18",
"img"=>"21"
);
foreach($img as $x=>$x_value)
{
$d = $html->find($x, $x_value);
echo $d->outertext;
}
The problem is that Simple HTML DOM is only returning the last image in array, which is number 21. What do I have to do to make it return everything in the array?
It's because both items in your $img array has the same key. foreach doesn't recognize them as two seperate items because both keys are img.
Example code to demonstrate:
$test = array(
"key" => 1,
"key" => 2
);
echo "Length of array: " . count($test) . "\n\n";
echo "Items in array:\n";
foreach($test as $key => $value) {
echo "$key => $value\n";
}
Outputs:
Length of array: 1
Items in array:
key => 2

Foreach loop, but for first key do something else

Sorry if this is confusing. It's tough for me to put into words having beginner knowledge of PHP.
I'm using the following foreach loop:
foreach ($_POST['technologies'] as $technologies){
echo ", " . $technologies;
}
Which produces:
, First, Second, Third
What I want:
First, Second, Third
All I need is for the loop to skip the echo ", " for the first key. How can I accomplish that?
You can pull out the indices of each array item using => and not print a comma for the first item:
foreach ($_POST['technologies'] as $i => $technologies) {
if ($i > 0) {
echo ", ";
}
echo $technologies;
}
Or, even easier, you can use implode($glue, $pieces), which "returns a string containing a string representation of all the array elements in the same order, with the glue string between each element":
echo implode(", ", $_POST['technologies']);
For general case of doing something in every but first iteration of foreach loop:
$first = true;
foreach ($_POST['technologies'] as $technologies){
if(!$first) {
echo ", ";
} else {
$first = false;
}
echo $technologies;
}
but implode() is best way to deal with this specific problem of yours:
echo implode(", ", $_POST['technologies']);
You need some kind of a flag:
$i = 1;
foreach ($_POST['technologies'] as $technologies){
if($i > 1){
echo ", " . $technologies;
} else {
echo $technologies;
}
$i++;
}
Adding an answer that deals with all types of arrays using whatever the first key of the array is:
# get the first key in array using the current iteration of array_keys (a.k.a first)
$firstKey = current(array_keys($array));
foreach ($array as $key => $value)
{
# if current $key !== $firstKey, prepend the ,
echo ($key !== $firstKey ? ', ' : ''). $value;
}
demo
Why don't you simply use PHP builtin function implode() to do this more easily and with less code?
Like this:
<?php
$a = ["first","second","third"];
echo implode($a, ", ");
So as per your case, simply do this:
echo implode($_POST['technologies'], ", ");

Categories