php multidimensional array iteration issue - php

Consider having 4 different RSS news feeds URL's
$urls[0]['news'] = "url1";
$urls[1]['news'] = "url2";
$urls[2]['news'] = "url3";
$urls[3]['news'] = "url4";
The following function should get 4 news titles from each of the url's
function getRssFeeds($urls,$type){
//Prepare XML objects
$xmls[$type] = array();
//Prepare item objects
$items[$type] = array();
//Prepare news titles/links arrays
$article_titles[$type] = array();
$encoded_titles[$type] = array();
$article_links[$type] = array();
//Fill XML objects
for($i=0; $i<4; $i++){
$xmls[$i][$type] = simplexml_load_file($urls[$i][$type]);
//Prepare news items
$items[$i][$type] = $xmls[$i][$type]->channel->item;
for($i=0; $i<4; $i++){
$article_titles[$i][$type] = $items[$i][$type]->title;
$encoded_titles[$i][$type] = iconv("UTF-8","windows-1251",$article_titles[$i][$type]);
}
//$article_links[$type][$i] = $items[$type][$i]->link;
}
return $encoded_titles;
}
After using the following to get the values:
type='';
function printRssFeed($urls,$type){
$titles = getRssFeeds($urls,$type);
foreach($titles as $title)
{
echo $title[$type]."<hr/>";
}
}
I get undefined offset error. If I remove the inner for loop of the getRssFeeds() function I get only 1 new title from each URL.

in this code you are resetting $i to 0 in your inner for loop.
for($i=0; $i<4; $i++){
$xmls[$i][$type] = simplexml_load_file($urls[$i][$type]);
//Prepare news items
$items[$i][$type] = $xmls[$i][$type]->channel->item;
for($i=0; $i<4; $i++){
$article_titles[$i][$type] = $items[$i][$type]->title;
$encoded_titles[$i][$type] = iconv("UTF-8","windows-1251",$article_titles[$i][$type]);
}
//$article_links[$type][$i] = $items[$type][$i]->link;
}
try changing your inner for loop variable to a different one. Also when you define your arrays it seems that you are not following the same structure.
$xmls[$i][$type] does not = your original instantiation of $xmls[$type] = array();
this is true for all your other arrays.
so I think your array structure is off because you add a top level of $type and then when you iterate you use a $i as you top level key.
try to remove the instantiations of the arrays in the beginning
function getRssFeeds($urls,$type){
//Fill XML objects
for($i=0; $i<4; $i++){
$xmls[$i][$type] = simplexml_load_file($urls[$i][$type]);
//Prepare news items
$items[$i][$type] = $xmls[$i][$type]->channel->item;
for($i=0; $i<4; $i++){
$article_titles[$i][$type] = $items[$i][$type]->title;
$encoded_titles[$i][$type] = iconv("UTF-8","windows-1251",$article_titles[$i][$type]);
}
//$article_links[$type][$i] = $items[$type][$i]->link;
}
return $encoded_titles;
}

try this in your inner for loop
$j = 0;
for($j=0; $j<4; $j++){
$article_titles[$j][$type] = $items[$i][$type]->title;
$encoded_titles[$j][$type] = iconv("UTF-8","windows-1251",$article_titles[$j][$type]);
}

Related

Get average of array subkey until other subkey contains "xx"

I'm trying to find a way to extract an average of a subkey of several arrays (up to 80) UNTIL another subkey has a certain value.
The full code contains the following:
$element = $html->find('table',3);
$i = 0;
foreach($element->find('tr') as $row){
if($i >= 2){
$racelapno = $row->find('td',0)->plaintext;
$racelaptime = $row->find('td',1)->plaintext;
$raceposition = $row->find('td',2)->plaintext;
$racetyre = $row->find('td',3)->plaintext;
$raceweather = $row->find('td',4)->plaintext;
$racetemp = $row->find('td',5)->plaintext;
$racehum = $row->find('td',6)->plaintext;
$raceevent = $row->find('td',7)->plaintext;
$racelap[$i] = Array();
$racelap[$i][0] = $racelapno;
$racelap[$i][1] = $racelaptime;
$racelap[$i][2] = $raceposition;
$racelap[$i][3] = $racetyre;
$racelap[$i][4] = $raceweather;
$racelap[$i][5] = $racetemp;
$racelap[$i][6] = $racehum;
$racelap[$i][7] = $raceevent;
}
$i+=1;
}
So I want to find the average of all $racetemp in the different arrays until an array returns "pit" on $raceevent.
Browsing on here I have found a way to find the average of all arrays which looks as followed:
$counter = 0;
$total = 0;
foreach($racelap as $row) {
$counter++;
$total += $row['5'];
}
$avgracetemp = $total / $counter;
But now I need to add some sort of stop when $racelap[$i][7] contains "pit", but also continue again until it contains "pit" again.
Hope anyone can help me, it is appreciated :)
If I understand you correctly, in foreach you can just use something like:
if (strpos($row['7'], 'pit') !== false) {
$counter++;
$total += $row['5'];
}

Get first value of array and store in new array php

I am trying to make card game.
I have 6 variable that are stored in array. Than I use fisherYates method to randomize array, and display four of them.
Problem is, when I randomize it this way only, it will give only random output of those six, with all different types.
So I want that some repeats like, if you draw four cards, you get output of
ex: club, club, diamond,heart, or heart, star,star,heart.. if you get a point..
I thought to do it like this way: put the array in loop of 4 times, and every time it loops, it stores first, or last value in new array, so that way, I can have greater chances of combination of same cards in output array.
But I'm stuck, and I don't know how to do it :/
this is what I've tried so far
$diamond = 'cube.jpg';
$heart = 'heart.jpg';
$spade = 'spade.jpg';
$club = 'tref.jpg';
$star='star.jpg';
$qmark='qmark.jpg';
$time=microtime(35);
$arr=[$diamond,$heart,$spade,$club,$star,$qmark];
function fisherYatesShuffle(&$items, $time)
{
for ($i = count($items) - 1; $i > 0; $i--)
{
$j = #mt_rand(0, $i);
$tmp = $items[$i];
$items[$i] = $items[$j];
$items[$j] = $tmp;
}
return $items;
}
$i=0;
do {
$niz[$i]=fisherYatesShuffle($arr,$time);
reset($niz);
$i++;
} while ($i <= 3);
Got a solution. Was just to simply do foreach of first element of multidimensional array :)
Code goes like this:
$diamond = 'cube.jpg';
$heart = 'heart.jpg';
$spade = 'spade.jpg';
$club = 'tref.jpg';
$star='star.jpg';
$qmark='qmark.jpg';
$time=microtime(35);
$arr=[$diamond,$heart,$spade,$club,$star,$qmark];
$niz=array();
$i=0;
do {
$niz[$i]=fisherYatesShuffle($arr,$time);
//reset($niz);
$i++;
} while ($i <= 3);
foreach ($niz as $key ) {
$randomArr[]=$key[0]; ;
}
function fisherYatesShuffle(&$items, $time)
{
for ($i = count($items) - 1; $i > 0; $i--)
{
$j = #mt_rand(0, $i);
$tmp = $items[$i];
$items[$i] = $items[$j];
$items[$j] = $tmp;
}
return $items;
}
print_r($randomArr);

Group and sum duplicate elements in a for loop

I have a for loop like so:
for((int) $i = 0; $i < $number_of_updates; $i++)
{
//query here
$result = mysql_query($query);
list($name) = mysql_fetch_row($result);
$points = 1;
//some functions to execute here... and then
//store results in session to show on other page
$output = $points.' times '.$name;
$_SESSION['item'][] = $output;
}
And then I show my results on view page like so:
foreach (array_unique($_SESSION['item']) as $output)
{
echo ('<p>'.$output.'</p>');
}
It echoes my results out of the loop like so:
1 times foo
1 times foo
1 times bar
1 times foo
etc...
Now the question. How do I sum those results up so they don't duplicate? Instead they are shown like so:
3 times foo
1 times bar
User array_count_values
for(/*(int) <- this is not neccessary (c++ background?) */ $i = 0; $i < $number_of_updates; $i++)
{
// your code
$_SESSION['item'][] = $name;
}
foreach(array_count_values($_SESSION['item']) as $name => $times)
echo ('<p>'.$times.' times '.$name.'</p>');
Of course counting the values directly is more memory and time efficient. This version is only neccessary if you somehow need to preserve the order of the elements.
Why didn't you store in your array directly the sum?
for((int) $i = 0; $i < $number_of_updates; $i++)
{
//query here
$result = mysql_query($query);
list($name) = mysql_fetch_row($result);
$points = 1;
//some functions to execute here... and then
//store results in session to show on other page
$_SESSION['item'][$name] +=$points;
}
Try this:
for((int) $i = 0; $i < $number_of_updates; $i++)
{
//query here
$result = mysql_query($query);
list($name) = mysql_fetch_row($result);
$points = 1;
//some functions to execute here... and then
//store results in session to show on other page
//$output = $points.' times '.$name;
//$_SESSION['item'][] = $output;
if( isset( $_SESSION['count'][$name] )){
$prev = $_SESSION['count'][$name];
}else{
$prev = 0;
}
$_SESSION['count'][$name] = $points + $prev ;
}
print_r( $_SESSION['count'] );

set string array from php?

I am a newbie in Php and this might be a quite basic question.
I would like to set string array and put values to array then get values which
I put to string array. so basically,
I want
ArrayList arr = new ArrayList<String>;
int limitSize = 20;
for(i = 0; i < limitSize; i++){
String data = i + "th";
arr.add(data);
System.out.println(arr.get(i));
};
How can I do this in php?
It's far less verbose in PHP. Since it isn't strongly typed, you can just append any values onto the array. It can be done with an incremental for loop:
$array = array();
$size = 20;
for ($i = 0; $i < $size; $i++) {
// Append onto array with []
$array[] = "{$i}th";
}
...or with a foreach and range()
foreach (range(0,$size-1) as $i) {
// Append onto array with []
$array[] = "{$i}th";
}
It is strongly recommended that you read the documentation on PHP arrays.
$arr = array();
$limitSize = 20;
for($i = 0; $i < $limitSize; $i++){
$data = $i . "th";
$arr[] = $data;
echo $arr[$i] . "\n";
}
In php arrays are always dynamic. so you can just use array_push($arrayName,$val) to add values and use regular for loop processing and do
for ($i=0; $i<count($arrName); $i++) {
echo $arr[$i];
}
to print /get value at i.

Why is my array only returning the last value in a loop?

I have the following code which is meant to cycle through names submitted on a form:
$row_count = count($_POST['name']);
if ($row_count > 0) {
mysql_select_db($database, $connection);
$name = array();
$workshop = array();
for($i = 0; $i < $row_count; $i++) {
// variable sanitation...
$name[i] = mysql_real_escape_string(ucwords($_POST['name'][$i]));
$workshop[i] = mysql_real_escape_string($_POST['workshop'][$i]);
}
$names = "('".implode("','",$name)."')";
.....etc
For some reason $names is only returning the last name submitted on the form, rather than all of the names. Could someone help me get this working correctly?
Thanks,
Nick
problem is here
$name[i] =
$workshop[i] =
solution:
$name[$i] =
$workshop[$i] =
now your code is working in this way:
$name["i"] =
$workshop["i"] =
so you have only one element in $name, $workshop arrays. (last from loop)

Categories