Display values without array (print_r) - php

I have a function that displays the actors photos from TMDB to my website is there a way that I can make it print without an array, it prints only with print_r I want to know if I can print it like echo or print.
This is the code:
public function getCasts($movieID)
{
if (empty($movieID)) return;
function cmpcast($a, $b)
{
return ($a["order"]>$b["order"]);
}
$temp = $this->_call("movie/" . $movieID . "/casts");
$casts = $temp['cast'];
$temp = array();
if (count($casts) > 0)
{
usort($casts, "cmpcast");
foreach ($casts as &$actor) {
if (!empty($actor['profile_path'])) {
for ($i=6; $i<count($temp['id']); $i++)
if ($temp['name'][$i] == $actor['name']) $temp['char'][$i] .= " / ".str_replace('(voice)', '(hang)', $actor['character']);
if (!in_array($actor['name'], (array) $temp['name'])) {
$temp['pic'][] = "<div style='margin-top:15px;' align='center'><div style='width:140px;margin-right:8px;display:inline-block;vertical-align:top;'><img style='width:130px;height:130px;border-radius:50%;' src='".$this->getImageURL().$actor['profile_path']."'><br />".$actor['name']."<br />".$actor['character']."</div></div>";
}
}
}
}
return $temp;
}

You could use some kind of loop. Use a for loop if you want to limit the number of item you echo.
For example :
$casts = getCasts(1);
for ($i = 0; $i < 5; $i++) {
if (isset($casts['pic'][$i])) {
echo $casts['pic'][$i];
}
}
Hope it helps.

Related

PHP foreach Group by Value

I am trying to group items within a PHP foreach by their 'field->value' and get the sum of each group separately. This code below works, but I feel like there is a more efficient way of doing it?
Thanks in advance.
<?php
$number_1 = 0;
$number_2 = 0;
$number_3 = 0;
foreach ( $fields as $field ) {
if($field->value == 1) {
$number_1 += $field->number;
}
if($field->value == 2) {
$number_2 += $field->number;
}
if($field->value == 3) {
$number_3 += $field->number;
}
}
echo $number_1;
echo $number_2;
echo $number_3;
?>
In this case you can use variable variables.
Generally I would rather recommend an array but it's your choice.
foreach ( $fields as $field ) {
${"number_" . $field->value} += $field->number;
}
Array version.
foreach ( $fields as $field ) {
$arr["number_" . $field->value] += $field->number;
}
// Either output as array or extract values to separate variables.
Echo $arr["number_1"];
//Or
Extract($arr);
Echo $number_1;
Edit had number where it should be value.
Don't use separate variables, use an array with $field->value as the index.
$numbers = array();
foreach ($fields as $field) {
if (isset($numbers[$field->value])) {
$numbers[$field->value] += $field->number;
} else {
$numbers[$field->value] = $field->number;
}
}

How to insert coordinates of a table into an array in PHP

I am making the game battleships in PHP and I need to make it so that the computer randomly chooses 5 coordinates(x, y), and they have to be in a straight line (column or row). How do I make it so the coordinates are in a line and how do I connect the coordinates to the table cells?
Here's what I have so far:
<?php
session_start();
$i=0;
$start=1;
$st=65;
$l=0;
$polje=array();
$x=(mt_rand(0, 10));
$y=(mt_rand(0, 10));
for($q=0; $q<5; $q++){
$polje[$l]=array($x, $y);
}
echo "<table id='table'>\n";
while ($i<11){
$ascii=chr($st);
echo "<tr>";
for($k=0; $k<11; $k++, $start++){
if($k==0){
echo "<td>$i</td>";
}
else if($i==0){
echo "<td class='td2'>$ascii</td>";
$ascii++;
}
else{
echo "<td class='td1'> </td>";
}
}
echo "</tr>";
$i++;
}
?>
This is what the table looks like:
I like this kind of challenge.
Of course, there is a lot of ways, better ways to do this, with OOP, but you can get the point.
Read the comments through the code and if you have any doubts feel free to ask.
I did some treatment to avoid ships overlapping each other, and random deployment.
const BOARD_SIZE = 10; //10x10 board
const SUBMARINE = 1;
const DESTROYER = 2;
const BATTLESHIP = 3;
const AIRCRAFTCARRIER = 4;
$ships_available = [];
//populate with some data based on game rule
array_push($ships_available, SUBMARINE);
array_push($ships_available, SUBMARINE);
array_push($ships_available, DESTROYER);
array_push($ships_available, DESTROYER);
array_push($ships_available, DESTROYER);
array_push($ships_available, BATTLESHIP);
array_push($ships_available, BATTLESHIP);
array_push($ships_available, AIRCRAFTCARRIER);
$board = [];
while(count($ships_available) > 0) {
deployShip($board, $ships_available);
}
$lastColumnLetter = chr(ord('A')+ BOARD_SIZE-1);
//print table
echo "<table border='1' align='center'>";
echo "<tr><td></td><td>".implode('</td><td>',range(1, BOARD_SIZE))."</td></tr>";
for($i = 'A'; $i <= $lastColumnLetter; $i++) {
echo "<tr><td>".$i."</td>";
for($j=0; $j < BOARD_SIZE; $j++) {
echo "<td align='center'>";
echo $board[$i][$j] ?: ' ';
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
exit;
function array_merge_custom($array1, $array2) {
foreach($array2 as $key => $value) {
foreach($value as $k => $v) {
$array1[$key][$k] = $v;
}
}
return $array1;
}
function deployShip(&$board, &$ships_available) {
$randomShipKey = array_rand($ships_available);
$ship = $ships_available[$randomShipKey];
$beginCoordinates = getRandomCoordinates();
$coordinates = getShipCoordinates($board, $beginCoordinates, $ship);
if(!$coordinates) {
return false;
}
unset($ships_available[$randomShipKey]);
$board = array_merge_custom($board,$coordinates);
}
function getRowNumberByLetter($letter) {
return array_search($letter, range('A','Z'));
}
function getRowLetterByNumber($number) {
$letters = range('A','Z');
return $letters[$number];
}
function getRandomCoordinates() {
return ['row' => chr(mt_rand(ord('A'), (ord('A') + BOARD_SIZE-1))), 'col' => mt_rand(0,BOARD_SIZE -1)];
}
function getShipCoordinates($board, $beginCoordinates, $ship) {
if(isset($board[$beginCoordinates['row']][$beginCoordinates['col']])) {
return false; //anchor position already taken
}
if($ship == 1) {
$return[$beginCoordinates['row']][$beginCoordinates['col']] = 1;
return $return;
}
$shipArraySize = $ship -1;
$directions = ['left', 'right', 'up', 'down'];
$tries = 10;
while($tries > 0) {
$tries--;
$direction = $directions[array_rand($directions)];
$return = [];
switch($direction) {
case 'left':
if(($beginCoordinates['col'] - $shipArraySize) < 0) { //check if can go left
break;
}
for($colBegin = ($beginCoordinates['col'] - $shipArraySize), $colEnd = $beginCoordinates['col']; $colBegin <= $colEnd; $colBegin++) {
if(!empty($board[$beginCoordinates['row']][$colBegin])) {
break 2;
} else {
$return[$beginCoordinates['row']][$colBegin] = $ship;
}
}
return $return;
case 'right':
if(($beginCoordinates['col'] + $shipArraySize) > BOARD_SIZE -1) { //check if can go right
break;
}
for($colBegin = $beginCoordinates['col'], $colEnd = ($beginCoordinates['col'] + $shipArraySize); $colBegin <= $colEnd; $colBegin++) {
if(!empty($board[$beginCoordinates['row']][$colEnd])) {
break 2;
} else {
$return[$beginCoordinates['row']][$colBegin] = $ship;
}
}
return $return;
case 'up':
if((getRowNumberByLetter($beginCoordinates['row']) - $shipArraySize) < 0) { //check if can go up
break;
}
for($rowBegin = (getRowNumberByLetter($beginCoordinates['row']) - $shipArraySize), $rowEnd = getRowNumberByLetter($beginCoordinates['row']); $rowBegin <= $rowEnd; $rowBegin++) {
if(!empty($board[getRowLetterByNumber($rowBegin)][$beginCoordinates['col']])) {
break 2;
} else {
$return[getRowLetterByNumber($rowBegin)][$beginCoordinates['col']] = $ship;
}
}
return $return;
case 'down':
if((getRowNumberByLetter($beginCoordinates['row']) + $shipArraySize) > BOARD_SIZE -1) { //check if can go down
break;
}
for($rowBegin = getRowNumberByLetter($beginCoordinates['row']), $rowEnd = (getRowNumberByLetter($beginCoordinates['row']) + $shipArraySize); $rowBegin <= $rowEnd; $rowBegin++) {
if(!empty($board[getRowLetterByNumber($rowBegin)][$beginCoordinates['col']])) {
break 2;
} else {
$return[getRowLetterByNumber($rowBegin)][$beginCoordinates['col']] = $ship;
}
}
return $return;
}
}
return false;
}

Adding PHP code in extension after every nth list element in TYPO3

I'm using old fashion way (kickstarter) to build extension in TYPO3. I would like to ad some PHP code after third element of list, but I really don't know how to do this.
My code looks like that:
protected function makeList($res) {
$items = array();
// Make list table rows
while (($this->internal['currentRow'] = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) !== FALSE) {
$items[] = $this->makeListItem();
}
$out = '<div' . $this->pi_classParam('listrow') . '>list items</div>';
return $out;
}
And:
protected function makeListItem() {
$out = 'list item details';
return $out;
}
If I understood correctly, you would need something like this:
protected function makeList($res) {
$items = array();
// Make list table rows
$i = 0;
$out = '<div' . $this->pi_classParam('listrow') . '>';
while (($this->internal['currentRow'] = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) !== FALSE) {
$out .= $this->makeListItem();
$i++;
if ($i == 3) {
$out .= '<img src="whateverjpg">';
$i = 0; // if you want to do it every 3 images
}
}
$out .= '</div>';
return $out;
}

PHP, listing things twice

I'm using this script to list a few Twitch.tv streams and their status (offline or online).
If there are no online streams found, I want it to display a text saying that all are offline.
Code that checks if the added streams are online:
//get's member names from stream url's and checks for online members
$channels = array();
for ($i = 0; $i < count($members); $i++) {
if (isset($json_array[$i])){
$title = $json_array[$i]['channel']['channel_url'];
$array = explode('/', $title);
$member = end($array);
$viewer = $json_array[$i] ['stream_count'];
onlinecheck($member, $viewer);
$checkedOnline[] = signin($member);
}
}
unset($value);
unset($i);
//checks if player streams are online
function onlinecheck($online, $viewers)
{
//If the variable online is not equal to null, there is a good change this person is currently streaming
if ($online != null)
{
echo ' <strong>'.$online.'</strong>';
echo '&nbsp <img src="/images/online.png"><strong> Status:</strong> Online! </br>';
echo '<img src="/images/viewers.png"><strong>Viewers:</strong> &nbsp' .$viewers.'</br>';
}
}
Full code:
<html>
<head>
<title>Streamlist</title>
</head>
<body>
<?php
$members = array("ncl_tv");
$userGrab = "http://api.justin.tv/api/stream/list.json?channel=";
$checkedOnline = array ();
foreach($members as $i =>$value){
$userGrab .= ",";
$userGrab .= $value;
}
unset($value);
$json_file = file_get_contents($userGrab, 0, null, null);
$json_array = json_decode($json_file, true);
$channels = array();
for ($i = 0; $i < count($members); $i++) {
if (isset($json_array[$i])){
$title = $json_array[$i]['channel']['channel_url'];
$array = explode('/', $title);
$member = end($array);
$viewer = $json_array[$i] ['stream_count'];
onlinecheck($member, $viewer);
$checkedOnline[] = signin($member);
}
}
unset($value);
unset($i);
function onlinecheck($online, $viewers) {
if ($online != null) {
echo ' <strong>'.$online.'</strong>';
echo '&nbsp <img src="/images/online.png"><strong> Status:</strong> Online! </br>';
echo '<img src="/images/viewers.png"><strong>Viewers:</strong> &nbsp' .$viewers.'</br>';
}
}
$alloffline = "All female user streams are currently offline.";
function signin($person){
if($person != null){
return $person;
}
?>
</body>
</html>
............................................................................................................................................................................
Is it because your $userGrab URL contains usernames twice? This is the URL whose contents you're retrieving:
http://api.justin.tv/api/stream/list.json?channel=painuser,ZombieGrub,Nathanias,Youbetterknowme,ncl_tv,painuser,ZombieGrub,Nathanias,Youbetterknowme,ncl_tv
Having looked at the response, it doesn't look like it's causing the problem. The strange URL is a result of you appending to the $userGrab string in the first foreach loop, after you've already added them with the implode() function call before. I think twitch.tv is rightly ignoring duplicate channels.
If all the values in $checkedOnline are null, everyone is offline. Put this at the end of your first code sample:
$personOnline = false;
foreach($checkedOnline as $person) {
if($person !== null) {
$personOnline = true;
break;
}
}
if(!$personOnline) {
echo 'No one is online';
}
else {
//there is at least someone online
}

Recursive function - tree view - <ul> <li> ... (stuck)

It seems that I'm stuck with my recursive function.
I have a problem with closing the unnamed list (</ul>) and the list-items (</li>)
The thing what i get is
-aaa
-bbb
-b11
-b22
-b33
-ccc
-c11
-c22
-c33
-ddd
-d11
-d22
-d33
-eee
-fff
And the thing what i want is:
-aaa
-bbb
-b11
-b22
-b2a
-b2c
-b2b
-b33
-ccc
-c11
-c22
-c33
-c2a
-c2c
-c2c1
-c2c2
-c2b
-ddd
-d11
-d22
-d33
-eee
-fff
This is the code that i'm using
$html .= '<ul>';
$i = 0;
foreach ($result as $item)
{
$html .= "<li>$item->id";
$html .= getSubjects($item->id, NULL, "",$i); <--- start
$html .= "</li>";
}
$html .= '</ul>';
And the function
function getSubjects($chapter_id = NULL, $subject_id = NULL, $string = '', $i = 0 ) {
$i++;
// getting the information out of the database
// Depending of his parent was a chapter or a subject
$query = db_select('course_subject', 'su');
//JOIN node with users
$query->join('course_general_info', 'g', 'su.general_info_id = g.id');
// If his parent was a chapter - get all the values where chapter id = ...
if ($chapter_id != NULL) {
$query
->fields('g', array('short_title', 'general_id'))
->fields('su', array('id'))
->condition('su.chapter_id', $chapter_id, '=');
$result = $query->execute();
}
// if the parent is a subject -
// get value all the values where subject id = ...
else {
$query
->fields('g', array('short_title', 'general_id'))
->fields('su', array('id'))
->condition('su.subject_id', $subject_id, '=');
$result = $query->execute();
}
// Because count doesn't work (drupal)
$int = 0;
foreach ($result as $t) {
$int++;
}
// if there no values in result - than return the string
if ($int == 0) {
return $string;
}
else {
// Creating a new <ul>
$string .= "<ul>";
foreach ($result as $item) {
// change the id's
$subject_id = $item->id;
$chapter_id = NULL;
// and set the string --> with the function to his own function
$string .= "<li>$item->short_title - id - $item->id ";
getSubjects(NULL, $subject_id, $string, $i);
$string .="</li>";
}
$string .= "</ul>";
}
// I thougt that this return wasn't necessary
return $string;
}
Does someone have more experience with this kind of things?
All help is welcome.
I am not sure what you are trying to do but here is some code you can test and see if it helps to solve your problem:
This part is just for testing, it makes three dimensional array for testing:
for ($x = 0; $x < 2; $x++) {
$result["c$x"] = "ROOT-{$x}";
for ($y = 0; $y < 3; $y++) {
$result[$x]["c$y"] = "SECOND-{$x}-{$y}";
$rnd_count1 = rand(0,3);
for ($z = 0; $z < $rnd_count1; $z++) {
$result[$x][$y]["c$z"] = "RND-{$x}-{$y}-{$z}";
$rnd_count2 = rand(0,4);
for ($c = 0; $c < $rnd_count2; $c++) {
$result[$x][$y][$z][$c] = "LAST-{$x}-{$y}-{$z}-{$c}";
}
}
}
}
// $result is now four dimensional array with some values
// Last two levels gets random count starting from 0 items.
UPDATE:
Added some randomness and fourth level to test array.
And here is function which sorts array to unordered list:
function recursive(array $array, $list_open = false){
foreach ($array as $item) {
if (is_array($item)) {
$html .= "<ul>\n";
$html .= recursive($item, true);
$html .= "</ul>\n";
$list_open = false;
} else {
if (!$list_open) {
$html .= "<ul>\n";
$list_open = true;
}
$html .= "\t<li>$item</li>\n";
}
}
if ($list_open) $html .= "</ul>\n";
return $html;
}
// Then test run, output results to page:
echo recursive($result);
UPDATE:
Now it should open and close <ul> tags properly.

Categories