Update associative array keys - php

I am having trouble updating the values of an multidimensional associative array. The array $people has been generated from another MySQL call. With :
array_push($people, array("forename" => $pat_f_name, "surname" => $pat_s_name,"id" => $id)); I have set $forname and $surname to "", just to have the key there.
I am trying to iterate though the array making an SQL call and retrieve the relevant forename and surname and then update the keys at that index of the array.
Below is my attempt so far.
Thanks in advance.
$stmt = $mysql->stmt_init();
foreach ($people as $person)
{
if($stmt->prepare("SELECT forename,surname FROM worker WHERE id = ?"))
{
$stmt->bind_param('i', $p_id);
$p_id = $person["id"];
$stmt->execute();
$stmt->bind_result($f_name, $s_name);
while($stmt->fetch())
{
$people[$person]["forename"] = $f_name;
$people[$person]["surname"] = $s_name;
}
}
}
$stmt->close();

$person is an array
$p_id = $person["id"];
this
$people[$person]["forename"] = $f_name;
should output:
Warning: Illegal offset type in ....
and
var_dump($people)
output
array(0) { }
better
foreach($people as $key => $person)
<your code>
$people[$key]["forename"] = $f_name;

I think the main problem here is that you try to use $person as index. Either you give your array ($people) a proper index or create a completely new array which you populate with your new $persons in your while-loop.
For the index solution add people to your array like this instead:
$people[$i++] = $person;
For the new array solution, create a new array and then populate it using:
$newPeople[] = $person;

Related

PHP - Access Multidimension array element

So currently I am having some issues with trying to access an element in this multidimensional array. So what I am trying to do is to create 3 different arrays of different classes, and then return them in array at the end.
The problem comes when I am trying to accsess one of the array's in the $result array. I have checked and there are elements in the array's but I am unable to access them.
public function search($searchString) : array
{
$bloggArr[] = array();
$bloggerArr[] = array();
$innleggArr[] = array();
$stmt = $this->db->prepare("SELECT * FROM blogg WHERE
bnavn=:bnavn");
$stmt->bindParam('bnavn', $searchString, PDO::PARAM_STR);
$stmt->execute();
while ($blogg=$stmt->fetchObject("Blogg"))
{
$bloggArr[]=array('blogg'=>$blogg);
echo $bloggArr['blogg']->hentBnavn();
// sort($bloggArr);
}
$stmt = $this->db->prepare("SELECT * FROM blogger WHERE
fornavn=:fornavn OR etternavn=:etternavn");
$stmt->bindParam('fornavn', $searchString, PDO::PARAM_STR);
$stmt->bindParam('etternavn', $searchString, PDO::PARAM_STR);
$stmt->execute();
while ($blogger = $stmt->fetchObject("Blogger"))
{
$bloggerArr[]= array('blogger' => $blogger);
// sort($bloggArr);
}
$stmt = $this->db->prepare("SELECT * FROM innlegg WHERE tittel=:tittel");
$stmt->bindParam('tittel', $searchString, PDO::PARAM_STR);
$stmt->execute();
while ($innlegg = $stmt->fetchObject("Innlegg"))
{
$innleggArr[] = array('innlegg' => $innlegg);
// sort($innleggArr);
}
$result = array('bloggArr' => $bloggArr, 'bloggerArr' =>
$bloggerArr, 'innleggArr' => $innleggArr);
return $result;
}
I thought I would be able to access the element in the second array by:
echo $resultat['bloggArr']['blogg']->SomeFunction();
the problem is that I get the error message that ['blogg'] is Undefined index. I am been unable to find a way to access the second array elements for a while now, and are wondering if anyone could point me in the right direction. Thanks for all help.
You're not using your arrays properly. Just considering $bloggArr:
$bloggArr[] = array();
creates this:
Array
(
[0] => Array
(
)
)
that line should be changed to:
$bloggArr = array();
To create an empty array. Then, each time through the loop,
$bloggArr[]=array('blogg'=>$blogg);
adds an element like this:
[1] => Array
(
[blogg] => <your object>
)
So, to access those values in the $result array you would need to use a loop:
foreach ($result['bloggArr'] as $blogg) {
echo $blogg['blogg']->SomeFunction();
}
If your queries will only return one result, then you could simply change this line:
$bloggArr[]=array('blogg'=>$blogg);
to
$bloggArr=array('blogg'=>$blogg);
and then you could access the function via
echo $result['bloggArr']['blogg']->SomeFunction();

Add element and key to array php

I'm trying to add an element to array, but I get a weird output. The code is the following:
$getalltokens = $db->query("SELECT * FROM Tables WHERE available = '$comp'");
while ($row = $getalltokens->fetch(PDO::FETCH_ASSOC))
{
$fid = $row['FID'];
$tok = $row['token'];
$sql = $db->query("SELECT Firstname,Lastname FROM Users WHERE Token = '$tok'");
$rez = $sql->fetch(PDO::FETCH_ASSOC);
$names[] = $rez;
$fidzy = array(
'FID' => $fid
);
array_push($names, $fidzy);
}
$getalltokens = $db->query("SELECT FID FROM Tables WHERE available = '$comp'");
$tokenz = $getalltokens->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($names);
And the output I get is:
[{"Firstname":"Test","Lastname":"Test"},{"FID":"5"},
{"Firstname":"Test2","Lastname":"Test2"},{"FID":"4"}]
While what I need is the FID to be inside the $names array, so it would be more like:
[{"Firstname":"Test","Lastname":"Test","FID":"5"}]
$rez['FID'] = $fid; /* Added */
$names[] = $rez;
/* $fidzy and array_push removed */
You can use instead of array_push() like
$arrayname[indexname] = $value;
if you use array_push()
<?php
$array[] = $var;
?>
Note: If you use `array_push()` to add one element to the array it's
better to use$array[] = because in that way there is no overhead of
calling a function.
Note: `array_push()` will raise a warning if the first argument is not an array. This differs from the `$var[]` behavior where a new array
is created.
Reference Array push
The solution to the specific problem at hand is selecting all the necessary data in a single query, removing the need to add elements to any array. This is done in the following fashion:
$sql = $db->query("SELECT
Users.Firstname,Users.Lastname,Tables.FID
FROM Users,Tables
WHERE Users.Token = Tables.token");
$rez = $sql->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rez);

SQL - Separate results by associated vale?

Before anything, I'll show you my table:
(In the context of PHP)
I'd like to create a multidimensional array via a query - So that a group of tags with the same id will end up in the same place:
<?php
// Given the above example table, it would essentially produce this:
$my_1 = array
( array('ect'),
array('123', 'tag'),
array('lolly', 'hat')
);
Is that a possibility? I've achieved the same result by looping through queries, but it's terribly inefficient.
<?php
$array = array();
foreach($tags as $tag)
{
if(array_key_exist($tag->id,$array)){
//if key is assigned in array, we can push value to key
$array[$tag->id] = array_push($tag->value,$array[$tag->id]);
}else{
//if key is not assigned we will create key and push value
$array[$tag->id] = $tag->value;
}
}
//usage
print_r($array[7]); // list tags with id 7
?>
Use a 2-dimensional array:
$array = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$id = $row['id'];
$tag = $row['tag'];
if (isset($array[$id])) {
$array[$id][] = $tag;
} else {
$array[$id] = array($tag);
}
}
The resulting $array will be
array(1 => array('ect'),
7 => array('123', 'tag'),
9 => array('lolly', 'hat'))

Add data in a multidimensional array dynamically

I am needing to add data dynamically into a multidimensional array. The data comes from a query in the database. I can see through the "echo" all elements, but in time to add to the multidimensional vector data and overwrite only the last record is added.
My example below:
$queryu = "SELECT * FROM usuario ORDER BY id";
$stmtu = $con->prepare($queryu);
$stmtu->execute();
$numu = $stmtu->rowCount();
$j = 0;
$lista;
if ($numu > 0) {
$colunas = 3;
while ($rowu = $stmtu->fetch(PDO :: FETCH_ASSOC)) {
extract($rowu);
$lista['id'] = $id;
$lista['nome'] = $nome;
$j++;
}
}
The result:
id - 6
nome - teste
This is the last record added.
Thanks!!!
You don't create a multi dimensional array by now. You just update create two key => value pairs id and nome. If you want to store multiple of them you have to create a multidimensional array which means an array inside another array:
$lista = array(); // init your array!
while ($rowu = $stmtu->fetch(PDO :: FETCH_ASSOC)) {
extract($rowu);
$lista[] = array(
'id' => $id,
'nome' => $nome
);
$j++;
}
Or do it even smarter (if the keys in the final array are the same as the column names):
$lista = array(); // init your array!
while ($rowu = $stmtu->fetch(PDO :: FETCH_ASSOC)) {
$lista[] = $rowu;
$j++;
}
Modify your code as follows
$queryu = "SELECT * FROM usuario ORDER BY id";
$stmtu = $con->prepare($queryu);
$stmtu->execute();
$numu = $stmtu->rowCount();
$lista = array();
if ($numu > 0) {
$colunas = 3;
while ($rowu = $stmtu->fetch(PDO :: FETCH_ASSOC)) {
extract($rowu);
$lista[] = array('id' => $id, 'nome' => $nome);
}
}
As you probably noticed here, I've removed j index (you don't need it; I suppose that you would use it as "first-level-index" of your multidimensional array) and added that statement: $lista[] =. "Magic" happens just there: with this command ($arrayname[] =) you can append to existent array a new element.
However I don't know from where you're obtaining $id and $nome so this snippet could fail due to undefined variables and similar

PHP PDO FetchAll arguments to remove row number from results

I am building a function that acts like Drupal's variable_initialize() function that pulls all key/value pairs into a global variable. I am trying to find the proper parameters I need to put into fetchAll() to remove the row number and get basically what fetch(PDO::FETCH_ASSOC) does but for all returned rows.
I basically want fetchAll to return:
Array {
[name] = value,
[name2] = value2,
[name3] = value3,
}
The variable table is a simple 2 column table (name)|(value)
function variable_init() {
global $db, $variable;
$query = "SELECT * FROM variable";
$stmt = $db->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll(); //need help here
foreach($result as $name => $value) {
$variable[$name] = $value;
}
}
I have tried PDO_COLUMN/PDO_GROUP/etc... but I can't seem to offset the array to remove the row numbers. Thanks.
I think you may be getting confused about what PDOStatement::fetchAll() returns.
The method returns all rows (arrays or objects, depending on fetch style) in an array.
Try this
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
$variable[$row['name']] = $row['value'];
}

Categories