How To Produce Multidimensional Array From While Loop? - php

I have this function :
function userKids(mysqli $Con, $Parent) {
$stmt = $Con->prepare('SELECT KidsName, KidsAge, KidsGender FROM Kids WHERE Parent = ?');
$stmt->bind_param('s', $Username);
$stmt->execute();
$Kid = null;
$Kids = array();
$stmt->bind_result($Kid, $KidsAge, $KidsGender);
while($stmt->fetch()) {
$Kids[] = $Kid;
}
return $Kids;
}
currently my WHILE loop produce array like this :
Array ( [0] => john [1] => jane )
Now, how to produce multidimensional array so I can get the Age and Gender as well, like this :
Array
(
[john] => Array
(
[0] => 3
[1] => male
)
[jane] => Array
(
[0] => 2
[1] => female
)
)

Change the line:
$Kids[] = $Kid;
To:
$Kids[$Kid] = array($KidsAge, $KidsGender);

I recommend that you use an associative array for the second dimension as well. So:
$Kids[$Kid] = array('age' => $KidsAge, 'gender' => $KidsGender);

replace the end of your code by:
$stmt->bind_result($KidName, $KidAge, $KidGender);
while($stmt->fetch()) {
$Kids[$KidName] = array($KidAge,$KidGender);
}
return $Kids;

Related

php mysql select for organizational chart / multi level structure

I have build my user table like this:
Now I would like to select the 3 blue rows.
I have build the following function:
function display_children($parent, $array = array()) {
global $db;
$stmt = $db->prepare("SELECT id AS man, parent_id FROM user WHERE parent_id= ?");
$stmt->execute(array($parent));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
display_children($row['man'], $array);
$array[] = array("man" => $row['man'], "parent_id" => $row['parent_id']);
echo $row['man']."\n"; //for debug
}
return $array;
}
print_r(display_children(50001));
My Output is:
50002
50004
50003
Array
(
[0] => Array
(
[man] => 50002
[parent_id] => 50001
)
[1] => Array
(
[man] => 50003
[parent_id] => 50001
)
)
The first three lines are correct, but the array is missing one.
The problem is, that the first parent_id has two rows. But the array is empty at the beginning. Is there a solution for my query?
the solution was to change the following line from
display_children($row['man'], $array);
to
$array = display_children($row['man'], $array);

How to compare different arrays?

I need to show the email address, first and last names of users who are not registered in my new database.
I selected three columns of my old database and three columns of my new database. I created two arrays and each receives the result of the query.
But when the comparing is displaying all users, the comparison is not made.
Check my code:
while($array = $resultado->fetch_array(MYSQLI_NUM)){
$portal_old[] = $array;
}
while($array2 = $resultado2->fetch_array(MYSQLI_NUM)){
$portal_new[] = $array2;
}
foreach ($portal_old as $portal) {
if(!in_array($portal, $portal_new)){
$result[] = $portal;
}
}
Assuming email address should be able to uniquely identify a registered user, you can use email address as a key as you build your array of results from each database.
while($array = $resultado->fetch_array(MYSQLI_ASSOC)){
$portal_old[$array['email']] = $array;
}
while($array2 = $resultado2->fetch_array(MYSQLI_ASSOC)){
$portal_new[$array2['email']] = $array2;
}
In order for this to work, you will need to either use MYSQLI_ASSOC instead of MYSQLI_NUM when fetching, and specify the name of the email column when building your array, or if you are using MYSQLI_NUM, specify the numeric index of the email column.
Then you can use array_diff_key to easily find the result you are looking for.
$result = array_diff_key($portal_old, $portal_new);
This works, John Smith here gets in $result while Joe Black doesn't:
<?php
$name = array(0 => 'john', 1 => 'smith');
$portal_old[] = $name;
$name = array(0 => 'joe', 1 => 'black');
$portal_old[] = $name;
//print_r($portal_old);
//shows: Array ( [0] => Array ( [0] => john [1] => smith ) [1] => Array ( [0] => joe [1] => black ) )
$name = array(0 => 'jason', 1 => 'mill');
$portal_new[] = $name;
$name = array(0 => 'joe', 1 => 'black');
$portal_new[] = $name;
//print_r($portal_new);
//shows: Array ( [0] => Array ( [0] => jason [1] => mill ) [1] => Array ( [0] => joe [1] => black ) )
foreach($portal_old as $key=>$value) {
if(!in_array($value[0], $portal_new[0]) && !in_array($value[1], $portal_new[1])) {
$result[] = $value;
}
}
print_r($result);
//shows: Array ( [0] => Array ( [0] => john [1] => smith ) )
?>
It's because the results of $portal_old and $portal_new are multidimensional arrays, you need to compare by looking inside the arrays of the arrays.
This will work for you :
$i = $j = 0;
while($array = $resultado->fetch_array(MYSQLI_NUM)){
$portal_old[$i][$array['0'].' | '.$array['1'].' | '.$array['2']] = $array;
}
while($array2 = $resultado2->fetch_array(MYSQLI_NUM)){
$portal_new[$j][$array2['0'].' | '.$array2['1'].' | '.$array2['2']] = $array2;
}
// Get only array keys
$old_arr_key = array_keys($portal_old[0]);
$new_arr_key = array_keys($portal_new[0]);
// Result
$result = array_diff($new_arr_key,$old_arr_key);
print_r($result);

PHP - Modify an array during foreach loop

public function getUserList($user_id){
$list_query = "SELECT ACTUAL_USER_ID FROM TABLE WHERE USER_ID = ".$user_id." ";
$result = parent::queryresult($list_query);
return $result;
}
foreach ($result as $uresult){ //$result contains user_id
$userlist[] = $classObject->getUserList($uresult['USER_ID']);
}
The loop outouts below
Array
(
[0] => Array
(
[0] => Array
(
[ACTUAL_USER_ID] => 133
)
)
[1] => Array
(
[0] => Array
(
[ACTUAL_USER_ID] => 122
)
)
)
How can I remove nested arrays and make it like below
Array
(
[0] => Array
(
[ACTUAL_USER_ID] => 133
)
[1] => Array
(
[ACTUAL_USER_ID] => 122
)
)
Use brackets [] to access array's elements
foreach ($result as $uresult){ //$result contains user_id
$userlist[] = $classObject->getUserList($uresult['USER_ID'])[0];
}
Edit: on different/old version of PHP you need to put array into variable first:
foreach ($result as $uresult){ //$result contains user_id
$row = $classObject->getUserList($uresult['USER_ID']);
$userlist[] = $row[0];
}
Change foreach statement as below
foreach ($result as $uresult){ //$result contains user_id
$res = $classObject->getUserList($uresult['USER_ID']);
if(isset($res[0]))
$userlist[] = $res[0];
}

Fetch all rows based on the query into an array and return single value

Fetch all rows based on the query into an array and return single value
Query database for data
//----------------------------------------------------------------------
$result = mysql_query("SELECT * FROM $tableName"); query
$array = mysql_fetch_row($result);
fetch result In Array
$arr = array();
while ($row = mysql_fetch_assoc($result)) {
$arr2 = array();
foreach ($row as $val) $arr2[] = $val;
$arr[] = $arr2;
}
Result Will Be
Array
(
[0] => Array
(
[0] => status_site
[1] => 0
)
[1] => Array
(
[0] => title_site
[1] => Script
)
[2] => Array
(
[0] => keys_site
[1] =>
)
)
I need to make function that return element 0 to 1
ex: function getsetting (title_site){
return value script}
Replace the $arr[] = $arr2; with $arr[$arr2[0]] = $arr2[1];. That might solve your problem.

Creating An Associative Multi Dimensional Array from loop in PHP

How can I create an array like the following in PHP from a database result set using a loop:
Array
(
[T] => Array
(
[0] => Array
(
[id] => 1
[name] => Timer
)
[1] => Array
(
[id] => 2
[name] => Tub
)
)
[P] => Array
(
[0] => Array
(
[id] => 3
[name] => Paper
)
[1] => Array
(
[id] => 4
[name] => Puppy
)
)
)
You will notice that the array keys are a letter, which is taken from the 'name' value in the result set. The loop will be something like this:
while($result = $db->fetch($query) {
$key = $result['name']{0};
// your answer :-)
}
I think something like this should do it:
$sql = 'SELECT id, name FROM table';
$result = mysql_query( $sql);
$answer = array();
while( $row = mysql_fetch_assoc( $result))
{
$answer[ strtoupper($row['name'][0]) ][] = $row;
}
mysql_free_result( $result);
var_dump( $answer);
OR, to be more specific (if your query is returning more columns than just id and name):
while( $row = mysql_fetch_assoc( $result))
{
$answer[ strtoupper($row['name'][0]) ][] = array(
'id' => $row['id'],
'name' => $row['name']
);
}
$indexArray = array(); // Array from Example
while($result = $db->fetch($query) {
$key = $result['name']{0};
if(!isset($indexArray[$key])) {
$indexArray[$key] = array();
}
array_push($indexArray[$key], $result);
}
$results = array();
while($result = $db->fetch($query)) {
$key = strtoupper($result['name'][0]);
if(!isset($results[$key]))
$results[$key] = array();
$results[$key][] = $result;
}

Categories