Hello there guys so first of all, I have this code:
$crumbs = array();
$crumbs[] = "Triple O Dental Laboratory";
if (is_array($GLOBALS["cookie_crumbs"])) {
foreach($GLOBALS["cookie_crumbs"] as $mycrumb) {
$mycrumb[1] = str_replace("//","/",$mycrumb[1]);
$crumbs[] = "".$mycrumb[0]." > Smile TRU";
}
}
print "<div class=\"cookie_crumbs2\">\n";
print implode(" > ",$crumbs);
print "</div>\n";
Now the problem is, i am trying to remove this part of the code:
> Smile TRU";
But only from the LAST item in the array, so pretty much at the moment its getting output like this: http://puu.sh/74ure.png
But I want the " > big one" taken away from the last item which is "Accreditation Video".
Try this :
$crumbs = array();
$crumbs[] = "Triple O Dental Laboratory";
if (is_array($GLOBALS["cookie_crumbs"])) {
foreach($GLOBALS["cookie_crumbs"] as $mycrumb) {
if(end($GLOBALS["cookie_crumbs"] != $mycrumb)){
$mycrumb[1] = str_replace("//","/",$mycrumb[1]);
$crumbs[] = "".$mycrumb[0]." > Smile TRU";
}
else{
$mycrumb[1] = str_replace("//","/",$mycrumb[1]);
$crumbs[] = "".$mycrumb[0]."";
}
}
}
print "<div class=\"cookie_crumbs2\">\n";
print implode(" > ",$crumbs);
print "</div>\n";
First count the crumbs and then, in the loop, check if You are handling the last one or not. Provided that the "cookie_crumbs" is array indexed numerically form 0:
$last = count($GLOBALS["cookie_crumbs"]) - 1;
foreach ($GLOBALS["cookie_crumbs"] as $index => $mycrumb) {
if ($index === $last) {
$crumbs[] = 'I am the last one'; // do whatever You need here...
}
else {
$mycrumb[1] = str_replace("//","/",$mycrumb[1]);
$crumbs[] = "".$mycrumb[0]." > Smile TRU";
}
}
Related
My objective is to create a multidimensional associative array with friends and their dreams (user input) in it. I think (hope) that I can am close to finishing it, but I get an unwanted result when echoing the final step:
I am trying to echo a sentence including the name of a 'friend' on line 22. Instead of a name inputted by the user, I get 'Array' as a result. E.g.: Array has this as their dream: Climbing Mount Everest
Does anyone know how I get the name of the friend here?
A line/string should be echoed for every separate dream that was filled in. And I included the print function for my clarity, will delete later. Thanks!
<?php
$friends = readline('How many friends should we ask for their dreams? ');
$array = [];
if (is_numeric($friends) == false) {
exit("This is not a number." . PHP_EOL);
} else if ($friends == 0) {
exit("This is not valid input." . PHP_EOL);
} else {
for ($i = 1; $i <= $friends; $i++) {
$name_key = readline('What is your name? ');
$number_dreams = readline('How many dreams are you going to enter? ');
for ($x = 1; $x <= $number_dreams; $x++) {
$dream_value = readline('What is your dream? ');
$array[$name_key][] = $dream_value;
}
print_r($array);
}
foreach ($array as $friend) {
foreach ($friend as $key => $value) {
echo $friend . ' has this as their dream: ' . $value . PHP_EOL;
}
}
}
try this after you assembled $array:
foreach ($array as $frndNm=>$dreams){
foreach($dreams as $dream){
echo( $frndNm.' dream is '.$dream);
}
}
I have problem with search in arrays , in 2 arrays , the first array have one structure fixed and the second send the vars from url and can have some values empty , for example
FIRST ARRAY :
The structure it's this :
id value , cat value , subcat value and country value
$ar_val="134567,dogs,food,EEUU";
The second var get from URL
$ar_url="134567,dogs,toys,EEUU";
As you can see in the second var , $ar_url i have one value no same to the first structure of $ar_val in this case toys
I want get compare the fixed structure of $ar_val and get if true or false if have same value in the same order from $ar_val
I try this :
$ar_val="134567,dogs,food,EEUU";
$ar_url="134567,dogs,toys,EEUU";
$exp_ar_val=explode(",",$ar_val);
$exp_ar_url=explode(",",$ar_url);
foreach ($exp_ar_val as $exp_ar_val2)
{
$ar_val_end[]=$exp_ar_val2;
}
foreach ($exp_ar_url as $exp_ar_url2)
{
$ar_val_end2[]=$exp_ar_url2;
}
$end_results=array_intersect($ar_val_end,$ar_val_end2);
With this I want know for example: If I search by id and for example for cat , get result positive in 2 arrays i have the same data , but if search for subcat i can´t get results because are differents in one have food and in other have toys , but with array_intersect no get this for compare
Thank´s , Regards
I think he wants to check if a value exists in either array. try this...
<?
function inarray($value,$array=array()){
if(in_array($value,$array)){
return true;
}else{
return false;
}
}
$ar_val=array("134567","dogs","food","EEUU");
$ar_url=array("134567","dogs","toys","EEUU");
$a = inarray("food",$ar_val);
$b = inarray("food",$ar_url);
if($a!=false and $b!=false)
echo "Found in both arrays";
elseif($a==true and $b==false)
echo "Found in first array";
elseif($a==false and $b==true)
echo "Found in second array";
else
echo "Not Found in any array";
?>
Try this:
$ar_val="134567,dogs,food,EEUU";
$ar_url="134567,dogs,toys,EEUU";
$arrayVal = explode(',', $ar_val);
$arrayUrl = explode(',', $ar_url);
$maxLength = max(sizeof($arrayVal), sizeof($arrayUrl));
$arrayIdsEqual = array();
$arrayIdsDifferent = array();
for ($i = 0; $i < $maxLength; $i++) {
if (isset($arrayVal[$i]) && isset($arrayUrl[$i])) {
if ($arrayVal[$i] == $arrayUrl[$i]) {
$arrayIdsEqual[] = $i;
}
else {
$arrayIdsDifferent[] = $i;
}
}
else {
//you arrive here if you have 2 arrays that don't have the same size / sme number of variables
}
}
//assuming your 2 arrays ALWAYS have the same size, you can use the following logic
if (empty($arrayIdsDifferent)) {
echo '2 arrays are the same';
}
else {
echo "Differences: \n";
foreach ($arrayIdsDifferent as $indexDifferent => $currentIdDifferent) {
$output = 'difference ' . ($indexDifferent + 1) . ': ';
$output .= 'val = ' . $arrayVal[$currentIdDifferent];
$output .= '; ';
$output .= 'url = ' . $arrayUrl[$currentIdDifferent];
echo $output;
echo "\n";
}
}
You can see this working here: http://3v4l.org/pTQns
You can use array_diff for this, which is perfect for comparison purposes:
<?php
$ar_val= array ("0" => "134567", "1" => "dogs", "2" => "food", "3" => "EEUU");
$ar_url= array ("0" => "134567", "1" => "dogs", "2" => "EEUU", "3" => "food");
$result = array_diff($ar_val, $ar_url);
$num = 0;
if ($result != NULL) {
echo "unique array keys: TRUE" . "\n\n";
print_r($result);
echo "\n\n";
} else {
echo "unique array keys: FALSE" . "\n\n";
}
foreach($ar_val as $key) {
if ($ar_val[$num] != $ar_url[$num]) {
echo "intersecting array key different: TRUE" . "\n> ";
print_r($ar_val[$num]);
echo "\n\n";
}
$num++;
}
?>
Just compare them with equal without any complicated operations.
$ar_val = "134567,dogs,food,EEUU";
$ar_url = "134567,dogs,toys,EEUU";
$exp_ar_val = explode(",", $ar_val);
$exp_ar_url = explode(",", $ar_url);
var_dump($exp_ar_val == $exp_ar_url); // false, elements does not match
$exp_ar_url = $exp_ar_val;
var_dump($exp_ar_val == $exp_ar_url); // true, all elements match
shuffle($exp_ar_url);
var_dump($exp_ar_val == $exp_ar_url); // false, different order
I have this piece of code
foreach($mnthArrPtrn as $m => $mn)
{
if(!isset($catName)) {
$catVals = array();
$prevCat = $catName = $pntChrtQry[0]['CAT']['categoryname'];
$pntVals .= '{name:'.$catName.',data:[';
}else if($prevCat != $catName) {
$prevCat = $catName;
$catVals = array();
$pntVals .= '{name:'.$catName.',data:[';
}
foreach($pntChrtQry as $key => $val){
$catName = $val['CAT']['categoryname'];
if($prevCat != $catName){
continue 2;
}
echo '<br />$m::'.$m;
echo '<br />$mn::'.$mn;
echo '<br />$val::'.$val[0]['MNTH'];
if($m == $val[0]['MNTH'] || $mn == $val[0]['MNTH']){
$catVals[] = $val[0]['total'];
}
}
pr($catVals);
if(!isset($catName)){
$pntVals .= ']},';
}
$catName = $val['CAT']['categoryname'];
}
1st loop iterates over a months array which are joined as a key value pair.
What I am doing here is on getting a new catName I continue the internal loop but at the same time I want to restart loop 1 with $prevCat,$catName still preserving their values.
Is this possible? Sorry If this is a silly question.
I tried converting the first one to a while statement and use a reset then but It didn't help me.
Something like this will allow you to arbitrarily restart a loop:
while (list($key, $value) = each($mnthArrPtrn)) {
if ($needToRestart) {
reset($mnthArrPtrn);
}
}
See more here.
I am currently using YouTube's API JSON-C response to pull data from a playlist and display the content in a list. I am doing this using PHP, however because YouTube restricts the maximum number of videos called, I have a hit a stumbling block. The maximum I can request is 50 whereas I have over 200 videos which I need to put in a list and I want to be able to do this dynamically.
I understand that I will have to loop the response, which is what I have done but is there a way it can be dynamically done?
If you could help me that would be great, my code is:
$count = 0;
foreach($data->data->items as $item) {
$count++;
echo $count." ".$item->id;
echo " - ";
echo $item->title;
echo "<br />";
if($count == 50) {
$query = "http://gdata.youtube.com/feeds/api/videos?q=USERNAME&start-index=50&max-results=50&v=2&alt=jsonc";
$data = file_get_contents($query);
if($data){
$data = json_decode($data);
foreach($data->data->items as $item) {
$count++;
echo $count." ".$item->id;
echo " - ";
echo $item->title;
echo "<br />";
}
}
}
if($count == 100) {
$query = "http://gdata.youtube.com/feeds/api/videos?q=USERNAME&start-index=100&max-results=50&v=2&alt=jsonc";
$data = file_get_contents($query);
if($data){
$data = json_decode($data);
foreach($data->data->items as $item) {
$count++;
echo $count." ".$item->id;
echo " - ";
echo $item->title;
echo "<br />";
}
}
}
}
and so on...
If you could help me out, or at least point me in the right direction that would be great, thanks.
One way is to loop over requests, and then over each item in the request. Like this:
$count = 1;
do {
$data = ...; // get 50 results starting at $count
foreach ($data->items as $item) {
echo "$count {$item->id} - {$item->title}<br />\n";
$count++;
}
} while (count($data->items) == 50);
Note that start-index is 1-based, so you have to query for 1, 51, 101 etc.
(This is actually quite similar to reading a file through a buffer, except with a file you've reached the end if the read gives you 0 bytes, while here you've reached the end if you get less than the amount you asked for.)
What I would do is first call the 4 pages, and then combine the results into 1 single array, then iterate over the data.
$offsets = array(0,50,100,150);
$data = array();
foreach($offsets as $offset)
{
$query = "http://gdata.youtube.com/feeds/api/videos?q=USERNAME&start-index=" . $offset . "&max-results=50&v=2&alt=jsonc";
$set = file_get_contents($query);
if(!emprty($set ))
{
$data = array_merge($data,json_decode($set));
}
}
//use $data here
Suppose I have a multi-dimensional array of the form:
array
(
array('Set_ID' => 1, 'Item_ID' => 17, 'Item_Name' = 'Whatever'),
array('Set_ID' => 1, 'Item_ID' => 18, 'Item_Name' = 'Blah'),
array('Set_ID' => 2, 'Item_ID' => 19, 'Item_Name' = 'Yo')
)
The array has more sub-arrays, but that's the basic form-- Items in Sets.
How can I loop through this array so that I can echo the number of items in each set along with the all the items like so:
Set 1 has 2 Items: 17: Whatever and 18: Blah
Set 2 has 1 Items: 19: Yo
I'm aware that this could be done with two loops-- one to build an array, and another to loop through that array. However, I'd like to do this all with only one loop.
In your answer, you should assume that there are two display functions
display_set($id, $count) //echo's "Set $id has $count Items"
display_item($id, $name) //echo's "$id: $name"
UPDATE: Forgot to mention that the data is sorted by Set_ID because its from SQL
Right, all the examples below rely on an ordered set, the OP states it is ordered initially, but if needed a sort function could be:
// Sort set in to order
usort($displaySet,
create_function('$a,$b',
'return ($a['Set_ID'] == $b['Set_ID']
? ($a['Set_ID'] == $b['Item_ID']
? 0
: ($a['Item_ID'] < $b['Item_ID']
? -1
: 1))
: ($a['Set_ID'] < $b['Set_ID'] ? -1 : 1));'));
Straight example using a single loop:
// Initialise for the first set
$cSetID = $displaySet[0]['Set_ID'];
$cSetEntries = array();
foreach ($displaySet as $cItem) {
if ($cSetID !== $cItem['Set_ID']) {
// A new set has been seen, display old set
display_set($cSetID, count($cSetEntries));
echo ": " . implode(" and ", $cSetEntries) . "\n";
$cSetID = $cItem['Set_ID'];
$cSetEntries = array();
}
// Store item display for later
ob_start();
display_item($cItem['Item_ID'], $cItem['Item_Name');
$cSetEntries[] = ob_get_clean();
}
// Perform last set display
display_set($cSetID, count($cSetEntries));
echo ": " . implode(" and ", $cSetEntries) . "\n";
Using a recursive function it could be something like this:
// Define recursive display function
function displayItemList($itemList) {
if (!empty($itemList)) {
$cItem = array_shift($itemList);
display_item($cItem['Item_ID'], $cItem['Item_Name');
if (!empty($itemList)) {
echo " and ";
}
}
displayItemList($itemList);
}
// Initialise for the first set
$cSetID = $displaySet[0]['Set_ID'];
$cSetEntries = array();
foreach ($displaySet as $cItem) {
if ($cSetID !== $cItem['Set_ID']) {
// A new set has been seen, display old set
display_set($cSetID, count($cSetEntries));
echo ": ";
displayItemList($cSetEntries);
echo "\n";
$cSetID = $cItem['Set_ID'];
$cSetEntries = array();
}
// Store item for later
$cSetEntries[] = $cItem;
}
// Perform last set display
display_set($cSetID, count($cSetEntries));
echo ": ";
displayItemList($cSetEntries);
echo "\n";
Amusingly, it can be one single recursive function:
function displaySetList($setList, $itemList = NULL) {
// First call, start process
if ($itemList === NULL) {
$itemList = array(array_shift($setList));
displaySetList($setList, $itemList);
return;
}
// Check for display item list mode
if ($setList === false) {
// Output first entry in the list
$cItem = array_shift($itemList);
display_item($cItem['Item_ID'], $cItem['Item_Name']);
if (!empty($itemList)) {
// Output the next
echo " and ";
displaySetList(false, $itemList);
} else {
echo "\n";
}
return;
}
if (empty($setList) || $setList[0]['Set_ID'] != $itemList[0]['Set_ID']) {
// New Set detected, output set
display_set($itemList[0]['Set_ID'], count($itemList));
echo ": ";
displaySetList(false, $itemList);
$itemList = array();
}
// Add next item and carry on
$itemList[] = array_shift($setList);
displaySetList($setList, $itemList);
}
// Execute the function
displaySetList($displaySet);
Note that the recursive example here is grossly inefficient, a double loop is by far the quickest.
<?php
$sets = array();
foreach ($items as $item)
{
if (!array_key_exists($item['Set_ID'], $sets))
{
$sets[$item['Set_ID']] = array();
}
$sets[$item['Set_ID']][] = $item;
}
foreach ($sets as $setID => $items)
{
echo 'Set ' . $setID . ' has ' . count($items) . ' Items: ';
foreach ($items as $item)
{
echo $item['Item_ID'] . ' ' . $item['Item_Name'];
}
}
?>
Something like this i guess?
EDIT:
After i posted this i saw the display functions where added. But you get the point.
The need to not print out any items until we know how many there are in the set makes this difficult. At some point, we'll need to doing some buffering, or else backtracking. However, if I'm allowed internal loops, and sets are contiguous in the "master" array, then with some hacking around:
$set = 0;
$items;
foreach ($arr as $a) {
if ($a['Set_ID'] != $set) {
if ($set != 0) {
display_set($set, count($items));
foreach ($items as $i)
display_item($i)
}
$set = $a['Set_ID'];
$items = array();
}
$items[] = $a;
}
How about this:
$previous_set = false;
$items = '';
$item_count = 0;
foreach ($rows as $row)
{
if ($row['Set_ID'] != $previous_set)
{
if ($previous_set)
{
echo display_set($row['Set_ID'], $item_count);
echo $items;
}
$previous_class = $row['Set_ID'];
$item_count = 0;
$items = '';
}
$items .= display_item($row['Item_ID'], $row['Title']);
$item_count++;
}
echo display_set($row['Set_ID'], $item_count);
echo $items;