php - Omitting columns in an array, with in another array - php

This is a fun one.
I have a function that produces an array from mySQL...or better yet, it produces an array of arrays. Follow?
I've figured out how to drill down in to the array to display them into a working table. As so:
<table id="list_table" cellpadding="1" cellspacing="1">
<?php
$array = $this->disparray;
foreach($array as $key => $value)
{
echo '<tr>';
foreach($value as $key => $value)
{
echo '<td>' . $value . '</td>';
}
echo '</tr>';
}
?>
</table>
HOWEVER, I only want to call specific <td>'s, which means, I have to call references to the specific column indexes. I've tried $value['1'], but it just does some crazy stuff. so, where I'm stuck is I do not know where to call the specific column indexes that I want.

You're nesting/overwriting your $key and $value variables. That is likely completely messing things up.
Try:
<?php
$array = $this->disparray;
foreach($array as $key => $value)
{
echo '<tr>';
foreach($value as $k => $v)
{
echo '<td>' . $v . '</td>';
}
echo '</tr>';
}
?>
That might help you solve your issues.

You stated " I have to call references to the specific column indexes" and "I just need to know how to specify which columns to use. (or which indexes/keys to display)".
I suspect your issue is actually more involved than this, but the answer to that question is to use the standard syntax for multidimensional arrays. E.g., $array['index1']['index2'].
More information about the PHP array syntax is here. Please clarify your question if you need more information.

Related

Manage a 4 dimensional array or a 5 dimensional with foreach statement in php

I am having a really bad time right now, since everyone on the internet is saying that PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people. So I can't find someone to help me.
A very simple example below
$documents = array(
array(
"name"=>"Markos",
"lastname"=>"papadopoulos",
"country"=>"Greece",
"nationality"=>"greek",
"job"=>"web developer",
"hobbies"=>array(
"sports"=>"boxing",
"others"=>array(
"freetime"=>"watching Tv"
)
)
)
);
foreach($documents as $document){
echo $document['name']."<br>"
.$document['lastname']."<br>"
.$document['country']."<br>"
.$document['nationality']."<br>"
.$document['job']."<br>";
foreach ($document['hobbies'] as $key=>$value){
echo $key." ".$value."<br>";
foreach ($value['others'] as $subkey=>$subvalue){
echo $subkey['freetime'];
}
}
}
I am stuck, I can't display the "others"=>array("freetime"=>"watching tv") can anyone advice me? And if I had also another array in the "others"=>array("freetime"=>"watching tv"), how could I display that array to? I am trying to learn the logic.
foreach ($documents as $key) {
echo $key['name']. '<br>';
echo $key['lastname']. '<br>';
echo $key['country']. '<br>';
echo $key['nationality']. '<br>';
echo $key['job']. '<br>';
echo $key['hobbies']['sports']. '<br>';
echo $key['hobbies']['others']['freetime']. '<br>';
}
output will be
Markos
papadopoulos
Greece
greek
web developer
boxing
watching Tv
In PHP, foreach actually have two syntaxes:
foreach($array as $element) this might means $element ends up being an array
foreach($array as $key => $value) this means that key will never be an array, it is what the key, so what you have before the => in your array, while $value can be an array.
Here is the way to follow the first syntax, mind that you don't even have to nest foreach here, as pointed out by #Nathanael's comment what you have in your array is mostly scalar, not really nested arrays.
foreach($documents as $document){
echo $document['name']."<br>".
$document['lastname']."<br>".
$document['country']."<br>".
$document['nationality']."<br>".
$document['job']."<br>".
$document['job']."<br>".
$document['hobbies']['sports']."<br>".
$document['hobbies']['others']['freetime'];
}
If you want to go in the second syntax, then it would be even better to make a recursion:
function display_multi_level_array($array) {
foreach($array as $key => $value){
if(is_array($value)) {
display_multi_level_array($value);
continue;
}
echo $key." ".$value."<br>";
}
}
display_multi_level_array($documents);
try
foreach($documents as $document){
echo $document['name']."<br>"
.$document['lastname']."<br>"
.$document['country']."<br>"
.$document['nationality']."<br>"
.$document['job']."<br>";
foreach ($document['hobbies'] as $key=>$value){
if (is_array($value)) {
foreach ($value as $subkey=>$subvalue){
echo $subvalue;
}
} else {
echo $key." ".$value."<br>";
}
}
}

Updating and Sorting a Multidimensional PHP Array

I have a mySQL query that dumps into an array, is sorted and then displayed, and that works perfectly.
My problem is that I want to update these values, re-sort them and display. I've been able to update the values, but it's within the same for loop and so it doesn't re-sort. So then I close the loop and re-sort but it doesn't save the updates I made in the first loop. Help is much appreciated.
foreach ($arr as $mks){
if ($mks['Column1']==$Var) {$mks['Column2'] = $mks['Column2'] + 1;
}
My sorting code
foreach ($arr as $mks){
echo $mks['Column1'] . ", " . $mks['Column2'] . "<br>";
}
How do I get this to re-save into my array properly?! I've tried googling this for most of the morning but has lead to frustration.
I think this is what you need:
foreach ($arr as $key => $mks){
if ($mks[$key] == $Var) {
$arr[$key] = $mks+1;
}
}
Now, $arr will contain the modified array, and you can use / modify it further as you need.
I don't see any "sorting code" but you can try to use references "&" instead of copy vars in your foreach(s) :
foreach($arr as & $mks){
...
}
Instead of copying your cells it will to give you a reference and every modifications done on it will be saved in the array.
Try changing your array like this instead
foreach ($arr as $key => $mks){
if ($mks['Column1']==$Var) {$arr[$key]['Column2'] = $mks['Column2'] + 1;
}

unserialize() value insert with serialize() of database.?

i insert in database values (array) with use function serialize(), how can echo they with unserialize() in tag <ul><li>...?
i have in database this: a:6:{i:0;s:15:"Coffee";i:1;s:14:"Satellite";i:2;s:11:"Game Notes";i:3;s:14:"Internet";i:4;s:10:"Pool";i:5;s:0:"";}
LIKE:
Coffee
Game Notes
Internet
Pool
You need to use unserialize(), as you said, with a foreach() loop, like this:
$arr = unserialize($dbString);
echo "<ul>";
foreach($arr as $key => $val)
{
echo "<li>$val</li>";
}
echo "</ul>";
This will echo a list containing value because foreach() iterates through the unserialize()d array, as you have specified in your question.
The $key => $part is the icing on the cake for foreach(); if you want the get the array key, simply reference $key. If you want the data for that key, use $val.
If you want to echo just one element (your example is Internet), just don't use a loop and reference it by key (integer):
$arr = unserialize($dbString);
echo $arr[2];
This echos the third element in the array on it's own.
Original question
Unserialize the data and loop over it printing it out. Notice that I have also added in checks to see that we are getting back an array and that it contains something before looping over it.
$data = unserialize($row['like']);
if(is_array($data) and count($data)) {
echo '<ul>';
foreach($like as $value) {
echo '<li>' . $value . '</li>';
}
echo '</ul>';
}
Internet
I think this is what you are asking for. To only echo out the value if its Internet.
$data = unserialize($row['like']);
if(is_array($data) and count($data)) {
echo '<ul>';
foreach($like as $value) {
if('Internet' != $value) {
continue;
}
echo '<li>' . $value . '</li>';
}
echo '</ul>';
}
JSON
If you can I would stop using serialize and use json_encode instead. It is easier to encode and decode in more programming languages and it is easier to edit by humans should you need to update the DB directly.

PHP : how to use foreach loop inside an echo statement?

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.

Multiple HTTP GET parameters with the same identifier

Let's say I am getting requests such as:
http://www.example.com/index.php?id=123&version=3&id=234&version=4
Is it possible to extract these in a simple way inside my php code? I realize I could get the entire querystring with javascript using window.location.href and handle it manually but I'm looking for something more elegant. The requests can contain any number of version/id pairs but I can assume that the query is well-formed and have no obligation to handle invalid strings.
If you can change the field name to include [], then PHP will create an array containing all of the matching values:
http://www.example.com/index.php?id[]=123&version[]=3&id[]=234&version[]=4
If you don't have the ability to change the field names, then as you say, you'll have to parse the querystring yourself.
According to this comment from the PHP manual, PHP's query string parser will drop duplicate params... so I don't think that PHP is a good fit for what you want to do (except in that it has the same capacity as javascript to get the raw query string, with which you can do whatever you want)
Assuming you have some control over the request, suffix the name with [] and PHP will generate arrays instead of dropping all but one.
http://www.example.com/index.php?id[]=123&version[]=3&id[]=234&version[]=4
Since they are pairs you'll probably want to fix the order they appear in using indexes.
http://www.example.com/index.php?id[0]=123&version[0]=3&id[1]=234&version[1]=4
Just extract the keys and values of $_GET, use the function as:
print_array('$_GET...',$_GET);
... and the function code will be:
function print_array($title, $arr) {
echo '<table width="100%" style="padding:10;">';
echo '<tr><td width="30%" style="text-align:right; background-color:bisque;">key of </td><td style="background-color:bisque;">'.$title.'</td></tr>';
foreach($arr as $key => $value) {
echo '<tr>';
echo '<td style="text-align:right; color:grey;">';
echo $key;
echo '</td>';
echo '<td>';
echo $value;
echo '</td>';
echo '</tr>';
}
echo '</table>';
}
Not as rounded or reliable as methods mentioned above but I use this to remove the need to [] in urls without worrying about rewriting.
$aQuery = explode("&", $_SERVER['QUERY_STRING']);
$aQueryOutput = array();
foreach ($aQuery as $param) {
if(!empty($param)){
$aTemp = explode('=', $param, 2);
if(isset($aTemp[1]) && $aTemp[1] !== ""){
list($name, $value) = explode('=', $param, 2);
$aQueryOutput[ strtolower(urldecode($name)) ][] = urldecode(preg_replace('/[^a-z 0-9\'+-]/i', "", $value));
}
}
}

Categories