문제

I have an XML string resulting from an SQL query that looks like the following (shortened). My website is set up to fetch this from SQL and $objRev->reviews->countries would give me the content of the countries part for each of the reviews in the XML.

Countries only contains text (country names) separated by comma and space.

In the below example my input variables would be:

var1 = "Austria, Belgium, Bulgaria, Croatia, Cyprus";
var2 = "Brazil, Sweden, United Kingdom";

Expected output: "Austria, Belgium, Brazil, Bulgaria, Croatia, Cyprus, Sweden, United Kingdom"

Can someone tell me how I can use PHP to combine the content of these variables in an array and sort them alphabetically ? My challenge here is that there are not always two variables, it can also be one or more as this depends on whether the review date matches a given input, here: 2014-04-21 - the indicator for this is dateMatch = 'Yes'.

<root>
  <reviews>
    <review>2014-04-21</review>
    <revLong>21 Apr 2014</revLong>
    <revShort>2014-04-21</revShort>
    <dayDiff>0</dayDiff>
    <revStatus>past</revStatus>
    <countries>Austria, Belgium, Bulgaria, Croatia, Cyprus</countries>
    <dateMatch>Yes</dateMatch>
    <countryMatch>Yes</countryMatch>
  </reviews>
  <reviews>
    <review>2014-04-21</review>
    <revLong>21 Apr 2014</revLong>
    <revShort>2014-04-21</revShort>
    <dayDiff>0</dayDiff>
    <revStatus>past</revStatus>
    <countries>Brazil, Sweden, United Kingdom</countries>
    <dateMatch>Yes</dateMatch>
    <countryMatch>No</countryMatch>
  </reviews>
</root>

Many thanks for any help with this, Tim.

도움이 되었습니까?

해결책

Something simple like this.. Use simplexml_load_string()

$xml = simplexml_load_string($xml);
foreach ($xml->reviews as $child)
{
        $cnt[]=explode(',',$child->countries);
}
$arr = array_map('trim',call_user_func_array('array_merge',$cnt));
sort($arr);
echo implode(', ',$arr);

OUTPUT :

Austria, Belgium, Brazil, Bulgaria, Croatia, Cyprus, Sweden, United Kingdom

Demonstration

다른 팁

Try with array_merge, sort and array_unique functions:

$all = array_unique(sort(array_merge($var1, $var2)));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top