Merge Arrays from XML feed [duplicate] - php

This question already has answers here:
Sorting XML with SimpleXML/XPath?
(3 answers)
Closed 9 years ago.
I am having a little trouble with an xml feed (atom). I am running a for each loop to return prices using simple xml and converting them too arrays which works fine below :-
foreach ($dc->departures->departure as $price)
{
$lowest = $price->prices->price[5]->asXML();
$lowestval = array($lowest);
print_r($lowestval);
}
Which is returning :-
Array ( [0] => 2289 )
Array ( [0] => 2207 )
Array ( [0] => 2369 )
Array ( [0] => 2229 )
My goal is to return only the lowest price, so I can display a Prices From: area. From what I understand I need to use the min() function, however this only works with one array with several values. I've tried array_merge which doesn't seem to work and just returns the same as above. I am a PHP newbie so there maybe something obvious. A kick in the correct direction would be appreciated.

Try this. Its working fine
<?php
foreach ($dc->departures->departure as $price)
{
$lowest = $price->prices->price[5]->asXML();
$lowestval[] = $lowest;
}
$min = min($lowestval);
echo $index = array_search($min, $array);
?>

$data = array();
$data[] =Array (0 => 2289 ) ;
$data[] = Array ( 0 => 2207 ) ;
$data[] = Array ( 0 => 2369 ) ;
$data[] = Array ( 0 => 2229 );
array_multisort($data);
$first = array_shift($data);
var_dump($first); // 2207

You can also use 'sort()' function to sort an array value.
Here is an example with some extra value as well merge array.
$arry1 = array(
array(5),
array(10000),
array(2289),
array(2288),
array(2207),
array(2369),
array(2229),
array(5421),
array(541)
);
$arry2 = array(
array(456789),
array(54564)
);
$arry1 = array_merge($arry1,$arry2);
sort($val);
echo '<pre>';
print_r($val);
echo '</pre>';
then you can use first element of an array as min value.
echo $arry1[0][0];

Related

Obtaining all values in php array [duplicate]

This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
I have the following array:
Array
(
[id] => 1043847
[company] => Array
(
[businesstype] => Array
(
[0] => Array
(
[id] => 6
[name] => Business Service Provider
)
[1] => Array
(
[id] => 8
[name] => Retailer
)
)
)
)
I would like to be able to get the value of company -> businesstype -> name for all the arrays inside businesstype so it would display like this:
Business Type(s): Business Service Provider, Retailer
Right now if I do this:
<?php echo($chamber_member['company']['businesstype']['name']); ?>
Nothing happens, if I do this:
<?php echo($chamber_member['company']['businesstype'][0]['name']); ?>
I get only the one for array [0]. How can I get both values separated by a comma like on the example above? Any help is appreciated, thank you in advance!!
This should work for you:
First get the column into an array with array_column(), then you can simply implode() this array ,e.g.
echo implode(",", array_column($chamber_member["company"]["businesstype"], "name"));
foreach($chamber_member['company']['businesstype'] as $a)
$b[] = $a['name'];
$result = implode(", ", $b);
Take names by array_column and cobine by implode
<?php echo implode(',', array_column($chamber_member['company']['businesstype'], 'name')); ?>
Try to loop into the array position with the 'businesstype' values:
for($i = 0; $i < count($chamber_member['company']['businesstype']); $i++){
echo $chamber_member['company']['businesstype'][$i]['name'] . ', ';
}
I like array_column() but for completeness, just foreach():
foreach($chamber_member['company']['businesstype'] as $array) {
echo $array['name'];
}
Or add to an array and implode().
Another solution using array_map():-
$arr=array
(
'id' => 1043847,
'company' => array
(
'businesstype' => array
(
array
(
'id'=> 6 ,
'name' => 'Business Service Provider'
),
array
(
'id' => 8,
'name' => 'Retailer'
)
)
)
);
echo $names = implode(',',array_map( function($person) { return $person['name']; },$arr['company']['businesstype']));
Use this. best answer for this..
$result=$chamber_member['company']['businesstype'];
$last=end($result);
for($i=0;$i<count($result);$i++)
{
$b[$i] = $result[$i]['name']; echo $b[$i]; if($last!=$result[$i]['name']){ echo ","; }
}

Flatten 2D Array Into Separate Indexed Arrays

I have the array:
$total =array();
Array (
[0] => Array
(
[0] => 1
[1] => 3
)
[1] => Array
(
[0] => 6
[1] => 7
[2] => 8
)
[2] => Array
(
[0] => 9
[1] => 10
)
)
I need to dynamically change each array into an indexed array for a Cartesian function.
Here is how I need the code to look for the function to work correctly:
$count = cartesian(
Array(1,3),
Array(6,7,8),
Array(9,10)
);
Any help would be greatly appreciated! I have tried flattening, looping, using array_values, using just the array itself and I keep falling short.
Thanks
Nick
function cartesian() {
$_ = func_get_args();
if(count($_) == 0)
return array(array());
$a = array_shift($_);
$c = call_user_func_array(__FUNCTION__, $_);
$r = array();
foreach($a as $v)
foreach($c as $p)
$r[] = array_merge(array($v), $p);
return $r;
}
$count = call_user_func('cartesian', array($total));
print_r($count);
Your arrays already look exactly the way you want them to. array(1,3) is the same as array(0 => 1, 1 => 3) and both are an array with the value 1 at key 0 and 3 at key 1. Exactly what the debug output shows you.
It seems you just need to pass them as separate arguments to the function. E.g.:
cartesian($total[0], $total[1], $total[2])
For dynamic lengths of arrays, do:
call_user_func_array('cartesian', $total)
I believe that your $total array is multi-dimensional array with numeric indexed. So yo can try like this
$count = cartesian($total[0], $total[1], $total[2]);

Get single column of data from mysql_query result [duplicate]

This question already has answers here:
How do I retrieve a single column from mysqli results
(5 answers)
Closed 6 months ago.
I am currently using a mysql_query with the UNION function. This is the array that I get:
Array
(
[0] => bob
[added] => bob
)
Array
(
[0] => test1
[added] => test1
)
Is there a way that I can take this array, merge it, remove the added values, place the data in numerical order and make it look like this?:
Array
(
[0] => bob
[1] => test1
)
I know somebody'll ask me what have I done so far. Honestly, I have no idea where to go from here.
array_reduce(
array_map(function($i) {
return $i[0];
}, $data),
function($result, $item) {
$result[] = $item;
return $result;
},
array()
);
or
call_user_func_array('array_merge',
array_map(function($i) {
return $i[0];
}, $data)
);
$array1=array_unique($array1);
$array2=array_unique($array2);
$result = array_merge ($array1,$array2);
When you are fetching the data you can create your array eg:
while($row = mysqli_fetch_array($result, MYSQLI_NUM){
$newArray[] = $row[0];
}
and from your current array you can do
$newArray = array();
foreach($array as $value){
$newArray = array_push($newArray,$value[0]);
}

PHP: Merging arrays with the same title

I have some php arrays from a loop, all of them bearing the same name. Now I want to merge them, but it seems not to work...
Here's my loop:
while($row = mysql_fetch_row($sql1)){
$startzeit=strtotime($row[2]);
$endzeit=strtotime($row[3]);
$startzeit_format = date("Y-m-d",$startzeit);
$endzeit_format = date("Y-m-d",$endzeit);
$datearray[] = createDateRangeArray($startzeit_format,$endzeit_format);
}
This should be the merging code:
for($i = 0; $i<count($datearray); $i++)
{
$datesarray = array_merge($datearray[$i]);
}
Anyway, the manual merge works fine:
$datesarray = array_merge( $datearray[0], $datearray[1], $datearray[2], $datearray[3]);
This one leads to the desired output. However I'd like to automatize it, as the single arrays come from a database and I won't add a $datearray[4], $datearray[5] and so on, everytime there is a new entry in the mySQL..
The result of print_r($datearray):
Array (
[0] => Array ( [0] => 2014-03-08 )
[1] => Array ( [0] => 2013-09-15 )
[2] => Array ( [0] => 2013-09-21 )
[3] => Array ( [0] => 2013-10-03
[1] => 2013-10-04
[2] => 2013-10-05
[3] => 2013-10-06 )
)
What you might be looking for is to flatten the array:
$datesarray = call_user_func_array('array_merge', $datearray);
It's identical to how you were manually merging together the array items.
See also: call_user_func_array()
You could also do this inside the loop with a simple loop:
$datesarray = array();
while ($row = mysql_fetch_row($sql1)) {
// ...
foreach (createDateRangeArray($startzeit_format,$endzeit_format) as $item) {
$datesarray[] = $item;
}
}
You are merging a single array to nothing.
$newArray = array_merge($array, $array)
Merges those two arrays but you are doing
$array = array_merge($datearray[$i]);
In affect, you are creating an array from one key of an array.

How do i sort multidimension array in PHP? [duplicate]

This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 5 months ago.
I have array like
Array (
[608665839] => Array ( [score] => 2 )
[1756044141] => Array ( [score] => 5 )
[523536777] => Array ( [score] => 2 )
)
and I want to sore this array by score. How can I do?
I would use uasort
I think [uasort()]1 function is helpful for sorting this array()
If multiple array then use array_[multisort()]2 functions
From PHP.net:
<?php
function order_array_num ($array, $key, $order = "ASC")
{
$tmp = array();
foreach($array as $akey => $array2)
{
$tmp[$akey] = $array2[$key];
}
if($order == "DESC")
{arsort($tmp , SORT_NUMERIC );}
else
{asort($tmp , SORT_NUMERIC );}
$tmp2 = array();
foreach($tmp as $key => $value)
{
$tmp2[$key] = $array[$key];
}
return $tmp2;
}
?>
$order = "ASC" will sort the array in an ascending order while $order = "DESC" will sort the array in a descending order.
Hope this helps.

Categories