How to decode an array? - php

I have this PHP array
$gender = array (
0 => array('Male','m.gif'),
1 => array('Female','f.gif'),
2 => array('Other','o.gif'),
);
And this ODBC
$DB = $core_db->Execute("SELECT ID, Name, Age, Location, Gender FROM Profiles
ORDER BY Name");
I want to use echo' . decode_gender($DB->fields[4], '2') . '; But I don't know how to make this decode function to connect that $DB->fields[4] is the same Gender from the array $gender in order to use it.

This function should do what you want. It takes the Gender value from the table lookup to index into the $genders array, and the second parameter to decide which value from the lookup array to return. Note that since you've said you want a value of 2 to return the second value in the array, you have to subtract one from the $idx value:
function decode_gender($gender, $idx) {
$genders = array (
0 => array('Male','m.gif'),
1 => array('Female','f.gif'),
2 => array('Other','o.gif'),
);
return $genders[$gender][$idx-1];
}
echo decode_gender(2, 2) . PHP_EOL;
echo decode_gender(1, 1) . PHP_EOL;
Output:
o.gif
Female
Demo on 3v4l.org

Related

PHP how do I get a formated result table of prepared statement as strings

I'm currently working on a small University project and I have to get into PHP. I have a score table where I want to get a ranked list back in PHP. The query works in phpmyadmin, but I just can't get my head around the prepared statement and how to get the results out of it. Here my code:
$con = getConnection ();
if (!$con) {
exit();
}
$stmt = $con -> prepare("SELECT NICKNAME, HIGHSCORE, #curRank := #curRank + 1 AS RANK FROM scores p, (SELECT #curRank := 0) r ORDER BY HIGHSCORE DESC;");
$stmt->execute();
$result = $stmt->get_result(); //$result is of type mysqli_result
$num_rows = $result->num_rows; //count number of rows in the result
// the '=' in the if statement is intentional, it will return true on success or false if it fails.
if (!$result_array = $result->fetch_assoc()) {
}
for ($j=0; $j<=$num_rows ;$j++){
$rows[$j]=$result->fetch_row();
print_r($rows[$j]);
}
mysqli_close($con);
}
and this is how the print_r looks like:
Array ( [0] => guvtg [1] => 234 [2] => 2 ) Array ( [0] => guvtgloa [1]
=> 228 [2] => 3 ) Array ( [0] => guvtgloakkschmua [1] => 226 [2] => 4 ) Array ( [0] => guvtgloakk [1] => 182 [2] => 5 )
As you can see I'm getting the whole array, but I just want and output like this:
guvtg , 234 , 2
guvtgloa , 228 , 3
etc..
Does anybody know how to get a proper result? Thank you
If you want to use fetch_assoc() it will give you an associative array with each item corresponding to a row field; will return FALSE when you are beyond the last row.
while ( $row = $result->fetch_assoc() ) {
echo $row[ 'NICKNAME' ] . "," . $row['HIGHSCORE'] . "," . $row['RANK'];
// maybe echo something at the end of the line (another comma or a line break....)
}
You don't have to get the row count but you shoud check that $result is not FALSE.
Similarly if you don't care about column names you may use fetch_row
while ( $row = $result->fetch_row() ) {
echo implode( ',', $row );
// maybe echo something at the end of the line (another comma or a line break....)
}
This way you can use implode to pack the data in comma separated values.
(But you have to handle what character to put between each row in outout)
Ex. if you want rows separated by line breaks (that will produce a CSV file) put echo "\n"; as the last statement inside the loop.
If you want a stream of comma separated values (no line breaks) then one solution is this:
$first = true;
while ( $row = $result->fetch_WOR() ) {
if( $first ) { $first = false; } else { echo ","; }
echo implode( ',', $row );
// maybe echo something at the end of the line (another comma or a line break....)
}
You'll allways get arrays from a database query, but it sounds like you just want to format the output differently. You could try this:
change
print_r($rows[$j]);
into
echo implode(', ', $rows[$j]), "\n";
implode will join the elements of every array with a comma+space in between, and by putting a newline after every record, the rows will each go on their own line.

Count variables from multidimensional array parts

I have a multidimensional array with emails
$emails = ( "emailid" => array( "email1", "email2" ,"email3" ) );
I want to count first part ($emails[]) of multi-dimension array and second part ($emails[][]). count($emails) only counts a whole array.
may be some one knows how.
Thank you!
You can use the COUNT_RECURSIVE flag to change how count works and get it to recursively count all items in your array regardless the depth. If you are just looking to get the count of the email addresses within the emailid sub array, you can access it directly by it's key.
$emails = ['emailid' => ['email1', 'email2', 'email3']];
// recursive count
echo count($emails, COUNT_RECURSIVE); // output 4
// normal count
echo count($emails); // output 1
// normal count using key
echo count($emails['emailid']); // output 3
What about this :
<?php
$emails = array("emailid" => array("email1","email2","email3"));
echo 'emails[] = ' . count($emails) . '<br />'; // result: 1
echo 'emails["emailid"] = ' . count($emails["emailid"]); // result: 3
?>

How can I efficiently search a field for flipped word order?

I have the following array.
$arr = array('foo','bar','foo-bar','abc','def','abc-def','ghi','abc-def-ghi');
I'm given a new string to decide to add to the array or not. If the string is already in the array, don't add it. If it is not in the array in its current form, but in a flipped word form is found, don't add it.
How should I accomplish this?
Examples:
'foo' —-> N - Do NOT add, already found
'xyz' —-> Y - Add, this is new
'bar-foo' —-> N - Do NOT add, already found in the flipped form 'foo-bar'
'ghi-jkl' —-> Y - Add, this is new
What do you recommend?
If you want to exclude items whose elements ('abc','ghi', etc.) are contained in another order and not only reversed, you could do:
$arr = array('foo','bar','foo-bar','abc','def','abc-def','ghi','abc-def-ghi');
function split_and_sort($str) {
$partsA = explode('-', $str);
sort($partsA);
return $partsA;
}
$arr_parts = array_map('split_and_sort', $arr);
$tests = array('foo','xyz','bar-foo','ghi-jkl');
$tests_parts = array_map('split_and_sort', $tests);
foreach($tests_parts as $test) {
if( !in_array($test, $arr_parts)) {
echo "adding: " . join('-', $test) . "\n";
$arr[] = join('-', $test);
}
else {
echo "skipping: " . join('-', $test) . "\n";
}
}
var_export($arr);
which outputs:
skipping: foo
adding: xyz
skipping: bar-foo
adding: ghi-jkl
array (
0 => 'foo',
1 => 'bar',
2 => 'foo-bar',
3 => 'abc',
4 => 'def',
5 => 'abc-def',
6 => 'ghi',
7 => 'abc-def-ghi',
8 => 'xyz',
9 => 'ghi-jkl',
)
Heres a suggestions on one way you can try...
for each string in $arr, reverse it as push into another array called $rev_arr
then...
$new_array = array();
foreach ($arr as $arr_1) $new_array[$arr_1] = true; // just set something
foreach ($rev_arr as $arr_2) $new_array[$arr_2] = true; // do also for reverse
now you can check what you want to do based on
if ( isset($new_arr[ $YOUR_TEST_VARIABLE_HERE ]) ) { // match found
}

PHP - Use everything from 1st array, remove duplicates from 2nd?

I have 2 arrays - the first one is output first in full. The 2nd one may have some values that were already used/output with the first array. I want to "clean up" the 2nd array so that I can output its data without worrying about showing duplicates. Just to be sure I have the terminology right & don't have some sort of "array within an array", this is how I access each one:
1st Array
$firstResponse = $sth->fetchAll();
foreach ($firstResponse as $firstResponseItem) {
echo $firstResponseItem['samecolumnname']; // Don't care if it's in 2nd array
}
2nd Array
while( $secondResponseRow = $dbRequest->fetch_assoc() ){
$secondResponseArray = array($secondResponseRow);
foreach ($secondResponseArray as $secondResponseItem){
echo $secondResponseItem['samecolumnname']; //This can't match anything above
}
}
Thanks!
For example:
$response_names = array();
$firstResponse = $sth->fetchAll();
foreach ($firstResponse as $firstResponseItem)
$response_names[] = $firstResponseItem['samecolumnname'];
while( $secondResponseRow = $dbRequest->fetch_assoc() ){
$secondResponseArray = array($secondResponseRow);
foreach ($secondResponseArray as $secondResponseItem) {
if (!in_array($secondResponseItem['samecolumnname'], $response_names))
$response_names[] = $secondResponseItem['samecolumnname'];
}
}
array_walk($response_names, function($value) { echo $value . '<br />' });
If I understand what you're looking to do and the arrays are in the same scope, this should work.
$secondResponseArray = array($secondResponseRow);
$secondResponseArray = array_diff($secondResponseArray, $firstResponse);
//secondResponseArray now contains only unique items
foreach ($secondResponseArray as $secondResponseItem){
echo $secondResponseItem['samecolumnname'];
}
If you know that the keys of duplicate values will be the same you could use array_diff_assoc to get the items of the first array that aren't in the other supplied arrays.
This code
<?php
$a = array('abc', 'def', 'ghi', 'adg');
$b = array('abc', 'hfs', 'toast', 'adgi');
$r = array_diff_assoc($b, $a);
print_r($a);
print_r($r);
produces the following output
[kernel#~]php so_1.php
Array
(
[0] => abc
[1] => def
[2] => ghi
[3] => adg
)
Array
(
[1] => hfs
[2] => toast
[3] => adgi
)
[kernel#~]

Echo only if it hasn't already been echoed?

What I'm trying to do is make a list of entries from a form, but I do not want the same entry to be displayed multiple times in the list if it was entered more than once in the form. For example, say one person enters "1" but then two people enter "2", I would only want the 2 to appear once in the list. What function would I be able to use for this?
The best way should be to store all your entries in an array (basic numerical indexed array) and then, remove duplicate with
uniqueEntries = array_unique($yourEntries);
The documentation : array_unique
example of code:
$entries = array();
$entries[] = 1;
$entries[] = 1;
$entries[] = 2;
$entries = array_unique($entries);
print_r($entries);
will output:
Array
(
[0] => 1
[2] => 2
)
In this case you should use PHP Arrays. Arrays are 2-dimensional tables.
/* Array
* key => value
* #key personID
* #value optionValue
*/
$array = array(
1 => 1, // Person 1 chose Option 1
2 => 2, // Person 2 chose Option 2
3 => 2 // Person 3 chose Option 2
);
print_r($array);
Prints
Array
(
[1] => 1
[2] => 2
[3] => 2
)
You are now able to fetch a set of unique values by accessing the array via array_unique($array);.
$array_unique = array_unique($array);
$array_unique_values = array_values($array_unique);
// Access array values directly and store into variables.
// Notice that arrays in PHP start with the index zero.
$option1 = $array_unique_values[0];
$option2 = $array_unique_values[1];
echo "Option #1: " . $option1 . "\n";
echo "Option #2: " . $option2;
Prints
Option #1: 1
Option #2: 2
Voilà.
You have no built-in function for that in PHP. But you could try with something like:
$echoList = array();
function echoOnce( $text )
{
global $echoList;
if(!in_array($text, $echoList)) {
echo $text;
$echoList[] = $text;
}
}
And then just use echoOnce( "whatever" ) instead of echo "whatever"

Categories