I have an array called $fields. If I do this:
foreach ($fields as $id => $field) {
print $id."<br />";
}
I get:
field_track_icon
field_session_number
field_job_title
I know this is totally simple, but my brain just will not come up with the answer, and I can't seem to google the right terms. How can I wrap the foreach in an if statement that's based on which id is being processed?
Pseudocode would be:
if($fields['field_session_number'] == 'S2') {
foreach($fields as $id=>$field) {
print $field->content;
}
}
Basically, I'm working with a single record of data returned in the $fields array. I only want to print out the individual field properties ($field->content or $field->prefix, for example) if the id of the field being processed is S2.
If you want to get element with specific key, you don't have to make for cycle - you just get it.
$field = $fields['field_session_number'];
echo $field->content;
echo $field->prefix;
If ID is not array key, but same as content or prefix, then you need for cycle:
foreach ($fields as $field) {
if ($field->id === 'S2') {
echo $field->content;
}
}
Related
I'm using the Kraken API to get a list of available currency pairings.
Here is the endpoint: https://api.kraken.com/0/public/AssetPairs
$kraken_coins =
file_get_contents('https://api.kraken.com/0/public/AssetPairs');
$kraken_coins = json_decode($kraken_coins, true);
foreach ($kraken_coins['result'] as $coin) {
echo $coin . "<br>";
}
I'm trying to extract the first element inside of "result", however each of these elements are named differently so I'm not sure how to target it. For example, the first two currency pairings returned are "BCHEUR" and "BCHUSD".
So with the loop I have above, it just echos "Array" repeatedly... not what I'm going for.
How do I target that element so I can loop through each one? Thanks!
Since, the json structure is:
You need to use:
foreach ($array as $key => $value) {
}
In this case:
foreach ($kraken_coins['result'] as $coin => $coindata) {
echo $coin . "<br>";
}
i want to display data from database and also i have created function in model file which is showing data from database but all values are shown in the array format.
problem is that when i print echo $values['title']; in foreach loop it is showing only first letter from title array??
model code
function reviewcitypage()
{
$cacheKey = 'city_page';
GigaCache::set(array('duration'=>"+1 minutes",'path'=>CACHE));
$cachedCategoryData = GigaCache::read($cacheKey);
if($cachedCategoryData && !cr('DynamicPage.field'))
{
$recentactivity = $cachedCategoryData;
}else
{
$recentactivity= $this->find("list",array("conditions"=>array("status"=>1),'fields'=>array('title','body','rating'),'recursive'=>-1,'limit'=>10));
//dont't set cache if dynamic field
if(!cr('DynamicPage.field'))
{
GigaCache::set(array('duration'=>"+1 minutes",'path'=>CACHE));
GigaCache::write($cacheKey,$recentactivity);
}
}
return $recentactivity;
}
view file
$ReviewObj = cri('Review');
$recentactivity = $ReviewObj->reviewcitypage();
foreach ($recentactivity as $name => $value){
foreach($value as $values)
{
echo $values['title'];
}
}
**problem is solved now thanks for support **
i have changed the code in model file and it is woking now
$recentactivity= $this-
>find("all",array("conditions"=>array("status"=>1),'recursive'=>-1,
'limit'=>10));
Your find() query is preparing the data as a 'list'. in cake lists are always key => value pair arrays. so in your view when you use the second foreach loop you are saying foreach character in a string...do.....
in your example $value can only be a string. foreaching it can only make $values a single char.
Let me know if you still unsure what i mean. not the best at explaining what i mean
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find-list
Because you are after 3 fields I suggest using either first or all in place of list as the first argument in the find() method.
I post a form with the same input names+id at the end like that:
<input type="text" name="machine_1">
<input type="text" name="machine_11">
<input type="text" name="machine_23">
How loop through on each of them and get the id's in the loop?
I tried this way, but it will loop a lot without any data and what happens if there is more thank 100 id?
for($i=0; $i<100; $i++){
$_POST["machine"]=$_POST["machine_".$i];
$id=$i;
}
POST is an associate array, so you can loop through everything that's been posted like this:
//$k contains the id
//$v contains the submitted value
foreach($_POST as $k => $v) {
//test if id contains 'machine'
if(stristr($k, 'machine')) {
echo $v;
}
}
You can do this using a foreach loop, like so:
foreach($_POST as $key => $value) {
echo "POST parameter '$key' has '$value';
}
$_POST["machine"]=$_POST["machine_".$i];
here $_POST['machine'] represents noting..how can you assign a value to $_POST['machine']..you havent passed any element having name machine while submitting the form..so first of all you need to check it bro
In your code, you have:
$_POST["machine"]=$_POST["machine_".$i];
That's not the correct way. You want to store the value of $_POST["machine_".$i] to $id and then use it below.
This is probably what you need:
for($i=1; $i<100; $i++){
$id = $_POST["machine_".$i];
echo $id;
}
And if there are more than 100 elements, and you don't know the number of inputs, then you can use a foreach loop, as below:
$i = 1; // counter variable
foreach ($_POST as $key => $input) {
if($key == "machine_".$i) {
$id = $input; // or simply 'echo $input'
echo $id;
}
$i++; // increment counter
}
I have been having an issue getting values out of an array that is formatted like so:
array(
[key]=>array(
[0]=>value
[1]=>value
[2]=>value)
[key]=>array(
[0]=>value
[1]=>value))
I am using a queue to run through each key as the queue item and process the information. so to create the queue item I have tried this:
while ($array = $result->fetchAssoc())
{
$queue->createItem($array);
}
this fails to create any items so I have used this method instead
if ($array != 0 || $array != NULL) {
foreach ($array as $row) {
$queue->createItem($row);
}
}
Once the queue item is created the queue calls a function passing the queue $item and here is where I have problems as I can successfully get all the values of the second level array but I can not access the Key of the first level.
function work_function($item){
foreach($item as $row=>$job){
//do something
}
}
In my function I have tried:
//1
$arrayKEY= $item;
//2
foreach($item as $row){
$arrayKEY= $row;
}
I just cannot get the values I need. What am I doing wrong/can I do to accomplish this?
Thanks
There's not much info here, but if the array is like you show, it's a multi-dimensional array, and thus needs 2 for loops.
function work_function($item){
foreach($item as $row=>$job){
echo "Row $row:\n";
foreach($job as $value){
echo $value."\n";
}
}
}
i am tring to put a loop to echo a number inside an echo ;
and i tried as bellow :
$array = array();
$result = mysql_query("SHOW TABLES FROM `st_db_1`");
while($row = mysql_fetch_row($result) ){
$result_tb = mysql_query("SELECT id FROM $row[0] LIMIT 1");
$row_tb=mysql_fetch_array($result_tb);
$array[] = $row[0];
$array2[] = $row_tb[0];
//checking for availbility of result_tb
/* if (!$result_tb) {
echo "DB Error, could not list tablesn";
echo 'MySQL Error: ' . mysql_error();
exit;
} */
}
natsort($array);
natsort($array2);
foreach ($array as $item[0] ) {
echo "<a href=show_cls_db.php?id= foreach ($array2 as $item2[0]){echo \"$item2[0]\"}>{$item[0]}<br/><a/>" ;
}
but php is not considering foreach loop inside that echo ;
please suggest me something
As mentioned by others, you cannot do loops inside a string. What you are trying to do can be achieved like this:
foreach ($array as $element) {
echo "<a href='show_cls_db.php?id=" . implode('', $array2) . "'>{$element}</a><br/>";
}
implode(...) concatenates all values of the array, with a separator, which can be an empty string too.
Notes:
I think you want <br /> outside of <a>...</a>
I don't see why you would want to used $item[0] as a temporary storage for traverser array elements (hence renamed to $element)
Just use implode instead of trying to loop the array,
foreach ($array as $item)
{
echo implode("",$array2);
}
other wise if you need to do other logic for each variable then you can do something like so:
foreach ($array as $item)
{
echo '<a href="show_details.php?';
foreach($something as $something_else)
{
echo $something_else;
}
echo '">Value</a>';
}
we would have to see the contents of the variables to understand what your trying to do.
As a wild guess I would think your array look's like:
array(
id => value
)
And as you was trying to access [0] within the value produced by the initial foreach, you might be trying to get the key and value separate, try something like this:
foreach($array as $id => $value)
{
echo $id; //This should be the index
echo $value; //This should be the value
}
foreach ($array as $item ) {
echo "<a href=\"show_cls_db.php?id=";
foreach ($array2 as $item2) { echo $item2[0]; }
echo "\">{$item[0]}<br/><a/>" ;
}
No offense but this code is... rough. Post it on codereview.stackexchange.com for some help re-factoring it. A quick tip for now would be to use PDO, and at the least, escape your inputs.
Anyway, as the answers have pointed out, you have simply echoed out a string with the "foreach" code inside it. Take it out of the string. I would probably use implode as RobertPitt suggested. Consider sorting and selecting your data from your database more efficiently by having mysql do the sorting. Don't use as $item[0] as that makes absolutely no sense at all. Name your variables clearly. Additionally, your href tag is malformed - you may not see the correct results even when you pull the foreach loop out of the echo, as your browser may render it all away. Make sure to put those quotes where they should be.