I have this code for an array, and the problem is that it shows only two last items of the array.
$svi= array(
$WMN1,
$LNG1,
$SSWN1,
$DT1,
$OET1,
$OW1,
$NT1
);
$imena_sajtova = array(
'Prvi WMN',
'Drugi LNG',
'Treci SSWN',
'Cetvrti DT',
'Peti OET',
'Sesti OW',
'Sedmi NT'
);
$novi_svi =array_combine($svi, $imena_sajtova);
echo '<pre>'; print_r($novi_svi); echo '</pre>';
And the result of this code is:
Array
(
[2] => Sedmi NT
[1] => Sesti OW
)
What could be a problem? Thanks!
var_dump($svi) displays this:
array(7) { [0]=> int(2) [1]=> int(1) [2]=> int(1) [3]=> int(1) [4]=> int(2) [5]=> int(1) [6]=> int(2) }
This $svi array has results from some functions:
$WMN1=RSS_Brojac($WMN);
$LNG1=RSS_Brojac($LNG);
$SSWN1=RSS_Brojac($SSWN);
$DT1=RSS_Brojac($DT);
$OET1=RSS_Brojac($OET);
$OW1=RSS_Brojac($OW);
$NT1=RSS_Brojac($NT);
I've changed order of arrays in the array_combine, and it works!
$novi_svi =array_combine($imena_sajtova, $svi);
arsort($novi_svi);
echo '<pre>'; print_r($novi_svi); echo '</pre>';
And the output of this code is:
Array
(
[Prvi WMN] => 2
[Sedmi NT] => 2
[Peti OET] => 2
[Sesti OW] => 1
[Cetvrti DT] => 1
[Drugi LNG] => 1
[Treci SSWN] => 1
)
I'have sorted them from high to low, that's what I actually wanted to do with this array.
Now, how to separate the results, to have them in separate divs inside html?
So then, I'll be able to change their style and create some kind of table with these results.
The results are output from some RSS feeds, which I use to count number of published news.
Thank you for your time!
Well there you go, the exact reason why you only retrieve two values after the array combine is because you've only supplied two unique integers, 1,2 as the indexes of the arrays to be combined. You need at least 7 unique values for your 7 strings.
Here's an example using your code and it doesn't work
And...Here's an example using 7 unique indexes, that does work
Typecast the values in the first array before merge. Can be achieved with array_map(). I assume you know the desired types in the variables.
Related
I'm studying php and I'm trying to figure out how to get the string "Juve_Milan" from this var_dump($_POST) :
array(5) {
["Juve_Milan"] => array(2) {
[0] => string(1)
"5" [1] => string(1)
"1"
}["Inter_Roma"] => array(2) {
[0] => string(1)
"4" [1] => string(1)
"4"
}["Napoli_Lazio"] => array(2) {
[0] => string(1)
"2" [1] => string(1)
"5"
}["name"] => string(0)
"" ["submit"] => string(5)
"Invia"
}
I could get all of them with:
foreach ($_POST as $param_name => $param_val) {
echo "<tr><td>".$param_name."</td><td>".$param_val[0]."-".$param_val[1]."</td></tr>";
}
But i want to get them exactly one by one, for example, if i want to get the string "Juve_Milan" or "inter_Roma" how can i do?
Without looping, how can i get the string value: "Juve_milan" or "Inter_Roma"? Becouse with the loop i can access them this way : $_POST as $param_name => $param_val
But i want to get them without loop, my first attempt was something like $_POST[0][0] but its wrong...
There are numbers of php array functions you can use.
You can use
array shift
to remove an element from an array and display it .e.g
$club = ['juve_millan', 'inter_roma', 'napoli_lazio'];
$juve = array_shift($club);
echo $juve;// 'juve_millan'
but note that the array is shortened by one element i.e. 'juve_millan' is no more in the array and also note that using
array_shift
over larger array is fairly slow
Array Slice function
PHP
array_slice()
function is used to extract a slice of an array e.g
$club = ['juve_millan', 'inter_roma', 'napoli_lazio'];
if I want to display
inter_roma
or assigned it to a variable, then I can do this
$roma = array_slice($club, 1, 1);// The first parameter is the array to slice, the second parameter is where to begin(which is one since most programming language array index start from 0 meaning juve_millan is zero, while inter_roma is 1, napoli_lazio is 2) and the length is 1 since i want to return a single element.
I hope you understand
You could iterate over keys of the main array like this:
foreach($_POST as $param_name => $param_val) {
echo "<tr><td>".$param_name."</td></tr>";
}
This will return each Juve_Milan, Inter_Roma etc. one by one. Although it's part of the code you already have, I believe this will return values you want only.
How to sort the following array?
I have an multidimensional array that gets filled with total hours for each brand
$totalHours = array(
'brand' => array(),
'project' => array(),
'hours' => array()
);
The output is something like this (project is not filled):
array(3) {
["brand"]=>
array(3) {
[0]=>
string(4) "Nike"
[1]=>
string(9) "Coke Cola"
[2]=>
string(8) "Converse"
}
["project"]=>
array(3) {
[0]=>
string(6) "Bonobo"
[1]=>
string(4) "LDRU"
[2]=>
string(2) "US"
}
["hours"]=>
array(3) {
[0]=>
int(28)
[1]=>
int(106)
[2]=>
string(1) "2"
}
}
Now I would like to sort the array based on the "hours" field.
I've tried the array_multisort but it seems like I simply don't get how this function works and how to apply it to this array.
I have been able to sort an single array with just one row of values. If I apply that to this problem im sorting only the hours field, leaving the others unsorted and therefore the array is corrupted.
The "project" does actually contains a string. It always does. In this example I didn't filled it.
array_multisort should work:
$totalHours = array(
'brand' => array('Nike', 'Coke Cola', 'Converse'),
'project' => array(),
'hours' => array(28, 106, '2')
);
array_multisort($totalHours['hours'], $totalHours['brand']);
var_dump($totalHours);
That data format is not very convenient because there is no direct association between brands and hours, they even sit in different arrays! Plus, the last hour is a string, not an integer.
We're going to have to create an intermediate array to associate them and sort them. We'll then re-inject everything in the original array.
// Make sure both arrays of brands and hours and the same size
if (count($totalHours['brand']) != count($totalHours['hours'])) {
throw new Exception('Invalid data!');
}
// Make sure every hour record is an integer, not a string
$totalHours['hours'] = array_map('intval', $totalHours['hours']);
// array_combine will sort all arrays based on the sorting of the first one
array_multisort($totalHours['hours'], $totalHours['brand'], $totalHours['project']);
EDIT: Using array_multisort was #delprks 's idea originally. Here I applied it to both brand and project arrays.
You cant do that with a single array_* function!
if (project is not filled) always and the indexes of brand and hours are equal, then you can do:
$forsort = array_combine($totalHours["brands"],$totalHours["hours"]);
asort($forsort,SORT_NUMERIC);
$totalHours["brands"]=array_keys($forsort);
$totalHours["hours"]=array_values($forsort);
But, this is just an answer for you question, not best practise at all.
I have these tables:
xml_documents table that has just one column, which is id
master_information table that has these columns id, xml_document_id, container, next_page
the relationship is one to one.
everything is working on my model. I can add, update, delete and every thing is working perfectly.
now I want to export my model as xml.
so I need to transfer my xmlDocument model to an array, then transfer this array to xml. I can do the second part myself, which is transfering php array to xml, but I don't know how to transfer the model to an array.
I tried this:
$xmlDocument = XmlDocument::find(4)->get()->toArray();
dd($xmlDocument)
but I got all the xml_document rows like this
array(2) { [0]=> array(1) { ["id"]=> int(4) } [1]=> array(1) { ["id"]=> int(5) } }
Then I tried this:
$xmlDocument = XmlDocument::find(4)->toArray();
dd($xmlDocument)
but I got this:
array(1) { ["id"]=> int(5) }
I need to also get the relationship. for example:
Array (
[id] = 4
[xmlInformation] => Array (
[id] => 1
[container] => 'bla'
[next_page] => 'bla bla'
)
can you help please?
Try this;
For a specific XmlDocument;
XmlDocument::with('MasterInformation', <... comma separated list of other relationships>)->find(4)->toArray();
For all XmlDocuments;
XmlDocument::with('MasterInformation', <... comma separated list of other relationships>)->get()->toArray();
I would like to push an associate array into another array but I an not sure how to go about it. At the minute I have the following:
$rate_info = array(
"hotel_rating" => $hotel->{'hotelRating'},
"room_rate" => $hotel->{'RoomRateDetailsList'}->{'RoomRateDetails'}->{'RateInfo'}->{'ChargeableRateInfo'}->{'#total'},
"currency" => $hotel->{'RoomRateDetailsList'}->{'RoomRateDetails'}->{'RateInfo'}->{'ChargeableRateInfo'}->{'#currencyCode'},
"deep_link" => $hotel->{'deepLink'}
);
array_push($hotel_array[$hotel->{'name'}]["offers"], "expedia" => $rate_info );
"Offers" is an array , all I want to do is add an key value with an array within in. Any ideas? All I seem to be getting at the minute is parse errors.
UPDATE
This is the output of the array so far
["offers"]=>
array(2) {
["LateRooms"]=>
array(4) {
["hotel_rating"]=>
int(4)
["room_rate"]=>
string(6) "225.06"
["currency"]=>
string(3) "USD"
}
[0]=>
string(4) "test"
}
As you can see instad of [0] I would like ["site"]=>array()
Thanks
Oliver
I'd do this for the array assignment:
$hotel_array[$hotel->name]['offers']['expedia'] = $rate_info;
Ensure your warnings are enabled, so you know arrays (and subarrays) have been set up before you use them.
Did you first do this?
$hotel_array[$hotel->{'name'}] = array();
And then you can do:
array_push($hotel_array[$hotel->{'name'}]["offers"], "expedia" => $rate_info );
I have the following array:
array(2) {
[0] => array(3) {
["submission_id"] => int(28)
["date"] => string(22) "2010-10-18 15:55:33+02"
["user_id"] => int(12)
}
[1] => array(3) {
["submission_id"] => int(37)
["date"] => string(22) "2010-11-21 16:02:07+01"
["user_id"] => int(23)
}
I want to get only the user_id key values from this array. I could obviously loop over it, but I was wondering if there was a quicker way.
You could use array_map (might not be quicker though, as it will make a function call per array element):
function getUserId($a) {
return $a['user_id'];
}
$user_ids = array_map('getUserId', $array);
Apart from that, looping is the only way (array_map makes loop anyway).
You can access only the user_id values like this if you know the array index you want to access:
$arr = your array here..
echo $arr[0]['user_id'];
echo $arr[1]['user_id'];