Return some values with PDO in function - php

i am using PDO to get some values of a table like : (table name is ban)
ID word
1 one
2 two
3 three
4 four
MY function is :
function retBans() {
global $connect;
$result = $connect->prepare("SELECT * FROM ban");
$result->execute();
$a = array();
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$a = $row['word'].",";
}
return $a;
}
and in the main php file, i wanted to get them back with this code :
$a = array();
$a = retBans();
$b = explode(",",$a);
print_r($b);
I wanted to have this :
Array {
[0] => one
[1] => two
[2] => three
[3] => four
}
But , it just return and print_r the last value (four) in array.
How can i get them like i said ?

Use this instead -
$a = '';
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$a .= $row['word'].",";
}
Then, you can use explode function
$a = retBans();
$b = explode(",",$a);
echo "<pre>"; print_r($b);

Related

How to compare JSON with ARRAY in PHP

I am trying to compare a JSON return with set ARRAY.
The JSON is showing OK, this is set as $a.
The ARRAY is coded and is showing OK, this is set as $b.
I'd like the output to be a percentage, not including duplicates.
THIS IS NOW EDITED.
<?php
$loggedUser = auth()->user()->id ; // returns authenticated user id.
$pdo = new PDO('mysql:host=****;dbname=****', '****', '****');
$stmt = $pdo->prepare('SELECT movie_id FROM user_watch_lists WHERE user_id = :user');
$stmt->execute(array('user' => $loggedUser));
$result_array = $stmt->fetchAll(PDO::FETCH_ASSOC);
$a = $result_array;
$b = array(297761);
print_r($a);
print_r($b);
$c = 0;
foreach ($a as $k=>$v) {
if ($v == $b[$k]) $c++;
}
echo ($c/count($a))*100;
?>
Contents of the return above (echo $a; and $echo b; and echo ($c/count($a))*100;):
Array ( [0] => Array ( [movie_id] => 297761 ) )
Array ( [0] => 297761 )
0
This should return 100%. I can see why, but unsure how to fix.
I've tried to change the loop to go in to the array but get ERROR.
foreach ($a as $r=>$k=>$v) {
if ($v == $b[$k]) $c++;
}
echo ($c/count($a))*100;

$array variable isn't equal to $GLOBALS['players'][$name] when defined as $GLOBALS['players'][$name] = array()

Using the code below it doesn't work but when I use
<?php
$GLOBALS['players'] = array();
function add($name) {
$array = $GLOBALS['players'][$name] = array();
array_push($array, "b");
}
add("a");
print_r($players);
?>
(outputs: Array ( [a] => Array ( ) )) the code here
<?php
$GLOBALS['players'] = array();
function add($name) {
$array = $GLOBALS['players'][$name] = array();
array_push($GLOBALS['players'][$name], "b");
}
add("a");
print_r($players);
?>
(outputs: Array ( [a] => Array ( [0] => b ) )) it works fine. Why does $array not work when it is referencing the same array.
It's very simple, when you pass the values to $array you're passing the $GLOBAL array to a new variable, you're not referencing the variable $GLOBAL variable.
In a few words: $array and $GLOBAL are two differents variables. Doing this is like doing:
$a = 10;
$b = $a;
$b++;
print_r($a); // Will not print 11, but 10, because you edited the var $b, that is different from $a.
To solve this little trouble you must pass the variable to $array by referencing it like here:
function add($name) {
$GLOBALS['players'][$name] = array();
$array = &$GLOBALS['players'][$name];
array_push($array, "b");
}

PHP bind_result and fetch multiple rows (array)

I'm fairly new to php and mysql. I'm trying to create a rest api from php, and because my server doesn't have mysqlndinstalled, I have to use bind_result and fetch.
$stmt = $this->conn->prepare("SELECT * from d WHERE d.id = ?");
$stmt->bind_param("i", 1);
if($stmt->execute()){
$stmt->bind_result($a, $b, $c);
$detail = array();
while($stmt->fetch()){
$detail["a"] = $a;
$detail["b"] = $b;
$detail["c"] = $c;
}
$stmt->close();
return $response;
} else {
return NULL;
}
Above code works but it can only return 1 line of information at a time.
For example if the statement return:
a b c
1 test test
1 test1 test1
it only returns
a: 1
b: test1
c: test1
where its supposed to be:
{
a: 1
b: test
c: test
},
{
a: 1
b: test1
c: test1
}
You're overwritting them, you could do something like this instead:
$detail = array();
while($stmt->fetch())
{
$temp = array():
$temp["a"] = $a;
$temp["b"] = $b;
$temp["c"] = $c;
$detail[] = $temp;
}
Or directly appending them with another dimension:
$detail = array();
while($stmt->fetch()) {
$detail[] = array('a' => $a, 'b' => $b, 'c' => $c);
// ^ add another dimension
}

Adding values to an Associative array

I'm tring to add new values to an associative array dynamically and I need your help.
Here is a simple example :
$a = array();
$a["name"]= "n1";
$a["age"]= "age1";
$a["name"]= "n2";
$a["age"]= "age2";
The result is:
Array (2){["name"]=>string(2) "n2" ["age"]=>string(4) "age2" }
I want to add The first age and name and the second age and name to the array. What can I do??
If you want to maintain name <=> age relationship :
$a = array();
$a[] = array("name"=>"n1","age"=>"age1");
$a[] = array("name"=>"n2","age"=>"age2");
UPDATE : usage example below :
foreach ($a as $assoc) {
echo $assoc["name"],' is ',$assoc["age"],'.<br />';
}
$a = array();
array_push($a, array("name"=>"n1","age"=>"age1"));
array_push($a, array("name"=>"n2","age"=>"age2"));
array_push
$a = array();
$a["name"][]= "n1";
$a["age"][]= "age1";
$a["name"][]= "n2";
$a["age"][]= "age2";
You can do by this way
$a = array(
array(
'name' => 'n1',
'age' => 'age1'
),
array(
'name' => 'n2',
'age' => 'age2'
)
);
That's very easy and simple, you can do whatever you want with arrays!! Any doubts? Here you go:
$a = array();
if(is_array($a) && i_can_answer())
{
$keys = array('age', 'name');
$anotherArray = array();
if(is_array($anotherArray ) && i_know_multi_dimensional_arrays())
{
array_push($anotherArray, array("+18", "ILovePHP"));
$result1 = array_combine($keys, $anotherArray);
}
$otherAnotherArray = array();
if(is_array($otherAnotherArray) && i_am_not_tired())
{
array_push($otherAnotherArray , array("+18", "ILovePHP"));
$result2 = array_combine($keys, $otherAnotherArray);
}
$a = array_merge($result1, $result2);
}
print_r($a); //// hoooorrraaaaaaaaaay

How do I redistribute an array into another array of a certain "shape". PHP

I have an array of my inventory (ITEMS A & B)
Items A & B are sold as sets of 1 x A & 2 x B.
The items also have various properties which don't affect how they are distributed into sets.
For example:
$inventory=array(
array("A","PINK"),
array("A","MAUVE"),
array("A","ORANGE"),
array("A","GREY"),
array("B","RED"),
array("B","BLUE"),
array("B","YELLOW"),
array("B","GREEN"),
array("B","BLACK")
);
I want to redistribute the array $inventory to create $set(s) such that
$set[0] => Array
(
[0] => array(A,PINK)
[1] => array(B,RED)
[2] => array(B,BLUE)
)
$set[1] => Array
(
[0] => array(A,MAUVE)
[1] => array(B,YELLOW)
[2] => array(B,GREEN)
)
$set[2] => Array
(
[0] => array(A,ORANGE)
[1] => array(B,BLACK)
[2] => NULL
)
$set[3] => Array
(
[0] => array(A,GREY)
[1] => NULL
[2] => NULL
)
As you can see. The items are redistributed in the order in which they appear in the inventory to create a set of 1 x A & 2 x B. The colour doesn't matter when creating the set. But I need to be able to find out what colour went into which set after the $set array is created. Sets are created until all inventory is exhausted. Where an inventory item doesn't exist to go into a set, a NULL value is inserted.
Thanks in advance!
I've assumed that all A's come before all B's:
$inventory=array(
array("A","PINK"),
array("A","MAUVE"),
array("A","ORANGE"),
array("A","GREY"),
array("B","RED"),
array("B","BLUE"),
array("B","YELLOW"),
array("B","GREEN"),
array("B","BLACK")
);
for($b_start_index = 0;$b_start_index<count($inventory);$b_start_index++) {
if($inventory[$b_start_index][0] == 'B') {
break;
}
}
$set = array();
for($i=0,$j=$b_start_index;$i!=$b_start_index;$i++,$j+=2) {
isset($inventory[$j])?$temp1=$inventory[$j]:$temp1 = null;
isset($inventory[$j+1])?$temp2=$inventory[$j+1]:$temp2 = null;
$set[] = array( $inventory[$i], $temp1, $temp2);
}
To make it easier to use your array, you should make it something like this
$inv['A'] = array(
'PINK',
'MAUVE',
'ORANGE',
'GREY'
);
$inv['B'] = array(
'RED',
'BLUE',
'YELLOW',
'GREEN',
'BLACK'
);
This way you can loop through them separately.
$createdSets = $setsRecord = $bTemp = array();
$bMarker = 1;
$aIndex = $bIndex = 0;
foreach($inv['A'] as $singles){
$bTemp[] = $singles;
$setsRecord[$singles][] = $aIndex;
for($i=$bIndex; $i < ($bMarker*2); ++$i) {
//echo $bIndex.' - '.($bMarker*2).'<br/>';
if(empty($inv['B'][$i])) {
$bTemp[] = 'null';
} else {
$bTemp[] = $inv['B'][$i];
$setsRecord[$inv['B'][$i]][] = $aIndex;
}
}
$createdSets[] = $bTemp;
$bTemp = array();
++$bMarker;
++$aIndex;
$bIndex = $bIndex + 2;
}
echo '<pre>';
print_r($createdSets);
print_r($setsRecord);
echo '</pre>';
To turn your array into an associative array, something like this can be done
<?php
$inventory=array(
array("A","PINK"),
array("A","MAUVE"),
array("A","ORANGE"),
array("A","GREY"),
array("B","RED"),
array("B","BLUE"),
array("B","YELLOW"),
array("B","GREEN"),
array("B","BLACK")
);
$inv = array();
foreach($inventory as $item){
$inv[$item[0]][] = $item[1];
}
echo '<pre>';
print_r($inv);
echo '</pre>';
Maybe you can use this function, assuming that:
... $inventory is already sorted (all A come before B)
... $inventory is a numeric array staring at index zero
// $set is the collection to which the generated sets are appended
// $inventory is your inventory, see the assumptions above
// $aCount - the number of A elements in a set
// $bCount - the number of B elements in a set
function makeSets(array &$sets, array $inventory, $aCount, $bCount) {
// extract $aItems from $inventory and shorten $inventory by $aCount
$aItems = array_splice($inventory, 0, $aCount);
$bItems = array();
// iterate over $inventory until a B item is found
foreach($inventory as $index => $item) {
if($item[0] == 'B') {
// extract $bItems from $inventory and shorten $inventory by $bCount
// break out of foreach loop after that
$bItems = array_splice($inventory, $index, $bCount);
break;
}
}
// append $aItems and $bItems to $sets, padd this array with null if
// less then $aCount + $bCount added
$sets[] = array_pad(array_merge($aItems, $bItems), $aCount + $bCount, null);
// if there are still values left in $inventory, call 'makeSets' again
if(count($inventory) > 0) makeSets($sets, $inventory, $aCount, $bCount);
}
$sets = array();
makeSets($sets, $inventory, 1, 2);
print_r($sets);
Since you mentioned that you dont have that much experience with arrays, here are the links to the php documentation for the functions I used in the above code:
array_splice — Remove a portion of the array and replace it with something else
array_merge — Merge one or more arrays
array_pad — Pad array to the specified length with a value
This code sorts inventory without any assumption on inventory ordering. You can specify pattern (in $aPattern), and order is obeyed. It also fills lacking entries with given default value.
<?php
# config
$aInventory=array(
array("A","PINK"),
array("A","MAUVE"),
array("A","ORANGE"),
array("A","GREY"),
array("B","RED"),
array("B","BLUE"),
array("B","YELLOW"),
array("B","GREEN"),
array("B","BLACK"),
array("C","cRED"),
array("C","cBLUE"),
array("C","cYELLOW"),
array("C","cGREEN"),
array("C","cBLACK")
);
$aPattern = array('A','B','A','C');
$mDefault = null;
# preparation
$aCounter = array_count_values($aPattern);
$aCurrentCounter = $aCurrentIndex = array_fill_keys(array_unique($aPattern),0);
$aPositions = array();
$aFill = array();
foreach ($aPattern as $nPosition=>$sElement){
$aPositions[$sElement] = array_keys($aPattern, $sElement);
$aFill[$sElement] = array_fill_keys($aPositions[$sElement], $mDefault);
} // foreach
$nTotalLine = count ($aPattern);
$aResult = array();
# main loop
foreach ($aInventory as $aItem){
$sElement = $aItem[0];
$nNeed = $aCounter[$sElement];
$nHas = $aCurrentCounter[$sElement];
if ($nHas == $nNeed){
$aCurrentIndex[$sElement]++;
$aCurrentCounter[$sElement] = 1;
} else {
$aCurrentCounter[$sElement]++;
} // if
$nCurrentIndex = $aCurrentIndex[$sElement];
if (!isset($aResult[$nCurrentIndex])){
$aResult[$nCurrentIndex] = array();
} // if
$nCurrentPosition = $aPositions[$sElement][$aCurrentCounter[$sElement]-1];
$aResult[$nCurrentIndex][$nCurrentPosition] = $aItem;
} // foreach
foreach ($aResult as &$aLine){
if (count($aLine)<$nTotalLine){
foreach ($aPositions as $sElement=>$aElementPositions){
$nCurrentElements = count(array_keys($aLine,$sElement));
if ($aCounter[$sElement] != $nCurrentElements){
$aLine = $aLine + $aFill[$sElement];
} // if
} // foreach
} // if
ksort($aLine);
# add empty items here
} // foreach
# output
var_dump($aResult);
Generic solution that requires you to specify a pattern of the form
$pattern = array('A','B','B');
The output will be in
$result = array();
The code :
// Convert to associative array
$inv = array();
foreach($inventory as $item)
$inv[$item[0]][] = $item[1];
// Position counters : int -> int
$count = array_fill(0, count($pattern),0);
$out = 0; // Number of counters that are "out" == "too far"
// Progression
while($out < count($count))
{
$elem = array();
// Select and increment corresponding counter
foreach($pattern as $i => $pat)
{
$elem[] = $inv[ $pat ][ $count[$i]++ ];
if($count[$i] == count($inv[$pat]))
$out++;
}
$result[] = $elem;
}

Categories