I have a database table (QUEUE) like this:
queueId phoneNumber
1 340 000
1 340 111 1
1 340 222
2 332 000
2 332 111
3 421 000
3 421 111
3 421 222
I use this query:
SELECT * FROM queue ORDER BY queueId
and this php code:
while ($rowQueue = mysql_fetch_array($resultQueryQueue, MYSQL_ASSOC)) {
$queue[] = array(
'queueId' => $rowQueue['queueId'],
'phoneNumber' => $rowQueue['phoneNumber']
);
}
result is a array with 8 arrays (beacuse record are 8).
I would like to get an array that contains arrays as there are so many keys. In my example I would like to get 3 arrays, the first key 1, the second and the third with key 2 and key 3.
How can I make PHP? Is there any function that can help me?
I think of two way to do that (off course there will be few other).
One you can do with mysql query IF "queryId" is a foreign key you can get all the phoneNumber associated with specific queryId
SECOND: i am Guessing you will get a result from query is like this
$arr = array(
array(
'queryid' => 1,
'phonenumber'=>350000
),
array(
'queryid' => 1,
'phonenumber'=>350000
),
array(
'queryid' => 2,
'phonenumber'=>340001
),
array(
'queryid' => 2,
'phonenumber'=>340002
)
);
You can sort this by
$ret = array();
foreach ($arr as $k => $v)
{
$ret [$v['queryid']][]=$v['phonenumber'];
}
var_dump($ret);
key of this array will be 'queryid' and will have array of phonenumber related to that key
And also consider removing space from phone number.
Let me know if it worked. thanks
Related
Is there an easy way to transform a one dimensional array into multidimensional array and along with that add a certain element to the newly created sub-arrays?
The countrycode always has 2 digits and appears only once before a set of locations. That's the element that I'd like to duplicate and add it to every subarray as shown below.
Thanks in advance!
That's what I have:
0 => AT
1 => Vienna-S03-I01
2 => 28 Users
3 => Vienna-S03-I02
4 => 25 Users
5 => Vienna-S03-I03
6 => 24 Users
7 => AU
8 => Sydney-S01-I01
9 => 45 Users
10 => BE
11 => Brussels-S01-I01
12 => 30 Users
13 => Brussels-S01-I02
14 => 37 Users
That's what I'd like to have:
0 =>
0 => AT
1 => Vienna-S03-I01
2 => 28 Users
1 =>
0 => AT
1 => Vienna-S03-I02
2 => 25 Users
2 =>
0 => AT
1 => Vienna-S03-I03
2 => 24 Users
3 =>
0 => AU
1 => Sydney-S01-I01
2 => 45 Users
4 =>
0 => BE
1 => Brussels-S01-I01
2 => 30 Users
5 =>
0 => BE
1 => Brussels-S01-I02
2 => 37 Users
If there is a guarantee that array will always follow rule you demonstrated, then code is below. Otherwise few condition check should be added there to make sure that we have proper value type in every given $item.
$array = ['AT',
'Vienna-S03-I01',
'28 Users',
'Vienna-S03-I02',
'25 Users',
'Vienna-S03-I03',
'24 Users',
'AU',
'Sydney-S01-I01',
'45 Users',
'BE',
'Brussels-S01-I01',
'30 Users',
'Brussels-S01-I02',
'37 Users'];
$code='none';
$result=[];
$resIndex=-1;
$swing=false;
foreach($array as $item){
if (strlen($item)===2){
$code=$item;
}else{
if ($swing===false){
$resIndex++;
$result[$resIndex][]=$code;
}
$result[$resIndex][]=$item;
$swing=!$swing;
}
}
print_r($result);
?>
This is a very light method in terms of function calls and variables. isset() is a very swift function call, so there will be minimal drag there. The snippet is condensed by declaring multiple variables in a single line ($result[++$i][]=$k=$v;) and by incrementing the counter (++$i) inside of the result array declarations.
Code: (Demo)
$array = ['AT',
'Vienna-S03-I01',
'28 Users',
'Vienna-S03-I02',
'25 Users',
'Vienna-S03-I03',
'24 Users',
'AU',
'Sydney-S01-I01',
'45 Users',
'BE',
'Brussels-S01-I01',
'30 Users',
'Brussels-S01-I02',
'37 Users'];
$i=-1;
foreach($array as $v){
if(strlen($v)==2){ // check for new Country ID
$result[++$i][]=$k=$v; // preserve Country ID as $k, store as a new batch
}else{
if(isset($result[$i][2])){ // when three elements in current batch, start new...
$result[++$i][]=$k; // increment counter and store preserved Country ID
}
$result[$i][]=$v; // add $v to batch
}
}
var_export($result);
p.s. as a matter of further micro-optimization, you could swap out strlen() for another isset() call -- but that is a bit less intuitive:
$i=-1;
foreach($array as $v){
if(!isset($v[2])){ // check for existence of character at offset 2
$result[++$i][]=$k=$v;
}else{
if(isset($result[$i][2])){
$result[++$i][]=$k;
}
$result[$i][]=$v;
}
}
This is a functional approach that doesn't need to iterate for each element in the array. I just love array_splice() and its fantastic dual action of extracting elements and shortening the input array:
// array_splice modifies the original array (shortens it) and returns the removed elements
while($array){
if(strlen($array[0])==2){ // if the first value is a Country id
$id=$array[0]; // preserve id
$result[]=array_splice($array,0,3); // cut away and preserve first three elements
}else{
$result[]=[$id]+array_splice($array,0,2); // store id and first two elements
}
}
var_export($result);
...and finally, my DRYest method:
while($array){
if(strlen($array[0])==2){ // if the first value is a Country id
$id=array_splice($array,0,1);
}
$result[]=array_merge($id,array_splice($array,0,2)); // store preserved id and two elements
}
var_export($result);
I have tried many ways to do this but no luck. I'm trying to take value from First array and generate second array and put the second array in the first array.
The code that I have now, generate the first array, in this array I have column called prereq_id I need to take this value and match it with courses table to bring its information in the courses table course_id=prereq_id. Any help would be highly appreciated
The array output is like this right now
[course_id] => 2
[curriculum_id] => 1
[set_number] => 0
[course_code] => GCIS 516
[course_name] => Data-Centric Concepts and Methods
[credits] => 3
[semester_ava] => 2
[prereq_id] => 10
[set] => 3
php
$result2 = $mysqli->query("SELECT *
FROM curriculumcourses
INNER JOIN courses ON curriculumcourses.course_id = courses.course_id
LEFT JOIN prerequisites ON courses.course_id=prerequisites.course_id
WHERE curriculum_id='$ids' ");
?>
<?php
for ($x = 1; $x <= $mysqli->affected_rows; $x++) {
$rows[] = $result2->fetch_assoc();
}
echo "<pre>";
print_r($rows);
echo "</pre>";
The result I need look like this
[course_id] => 2
[curriculum_id] => 1
[set_number] => 0
[course_code] => GCIS 516
[course_name] => Data-Centric Concepts and Methods
[credits] => 3
[semester_ava] => 2
[prereq_id] => 10
[set] => 3
[course_code] => GCIS 508
[course_name] =>Database Management Systems
[credits] => 3
[semester_ava] => 1
My Problem
Trying to create similar arrays so I can compare them.
I am creating a distribution list for files, the adding of the distribution list work fine, I list user surname, user forename and user department, these are selected and posted, foreach user I retrieve the users.user_id and store this in a distribution table (under distro_lis)t like so.
distro_id (AI, PK) | distro_list | policy_id
---------------------------------------------
1 | 1 23 21 34 | 13
2 | 10 22 21 34 | 15
3 | 1 27 26 40 | 34
Now I working on the editing of the distribution list, so for a row, lets say row 1, I fetch the distro_list and parse it to get each user ID (from distro_list) using.
$policyID is received in the method argument
$db = $this->dbh->prepare('SELECT distro_list FROM distro WHERE policy_id = :policy_id');
$db->bindParam(':policy_id', $policyID);
$db->execute();
$row = $db->fetch(PDO::FETCH_ASSOC);
$ids = explode(' ',$row);
foreach ($ids as $user) {
$db = $this->dbh->prepare('SELECT user_forename, user_surname, user_dept FROM users WHERE user_id = :user_id ORDER BY user_surname ASC');
$db->bindParam(':user_id', $user);
$db->execute();
$row = $db->fetch(PDO::FETCH_ASSOC);
var_dump($row);
}
the var_dump($row) returns an array of arrays (objects.. not sure of the terminology here) which looks like so (print_r).
Array
(
[user_forename] => fname1
[user_surname] => sname1
[user_dept] => dept1
)
Array
(
[user_forename] => fname2
[user_surname] => sname2
[user_dept] => dept2
)
Array
(
[user_forename] => fname3
[user_surname] => sname3
[user_dept] => dept3
)
the array that I want to compare it to looks like so (print_r).
array
(
[0] => Array
(
[user_forename] => fname1
[user_surname] => sname1
[user_dept] => dept1
)
[1] => Array
(
[user_forename] => fname2
[user_surname] => sname2
[user_dept] => dept2
)
[2] => Array
(
[user_forename] => fname3
[user_surname] => sname3
[user_dept] => dept3
)
)
I understand why the first array looks like that, because im var_dump'ing' after each iteration. How can I get the first array (array of arrays or objects) into a single array so I can compare it to the second array?
Try this
$list_users = array()
foreach ($ids as $user) {
//...
$list_users[] = $row;
}
var_dump($list_users);
I am trying to extract only array items that match on specific fields and then I need to merge the two into one array only containing the data I need.
I have two arrays, and their structure is like below. Only product_count s where CATEGORY_ID of Array #1 match the Key of Array #2 should be the output.
Array #1: - Many of Array #1 CATEGORY_IDs will not exist in Array #2 key field.
0 => Array (4)
0 => 3
CATEGORY_ID => 10
1 => 1
product_count => 8
1 => Array (4)
0 => 4
CATEGORY_ID => 111
1 => 6
product_count => 109
...
Array #2:
10 => Category Name 1
110 => Category Name 2
8 => Category Name 3
109 => Category Name 4
111 => Category Name 5
3 => Category Name 6
132 => Category Name 7
...
Final Output should look something like: and I might be going about this all wrong, so I am open to any suggestions..
10 => [0] => Category Name 1
[1] => 8 // product_count
111 => [0] => Category Name 5
[1] => 109 // product_count
...
I am running a foreach() to extract product counts per category. As you can see my two arrays reflect this by the data.
You'd have to do a foreach loop, I believe:
$new_array = array();
foreach($array1 as $part) {
$new_array[$part["CATEGORY_ID"]] = array( $array2[$part["CATEGORY_ID"]], $part["product_count"] );
}
I think I got the gist of what you want. I don't think there is an actual PHP function to do what you want, either.
The array:
array(
'354' => array(
'parent' => 0
),
'370' => array(
'parent' => 0
),
'420' => array(
'parent' => 354
),
)
How can I move all elements that have the 'parent' value != 0, just after the element to which the key is the same as that parent value?
For example, the element with the 420 keys above needs to go after the element with the 354 key...
That's impossible in the general case. In your example it would work.
But here's another example:
Number | Parent
10 | 1
11 | 1
100 | 10
101 | 10
102 | 10
1000 | 100
1001 | 100
So you want that all the three rows 100, 101, 102 come directly after the row 10, which is impossible.
And between row 100 and 101 you probably want the rows 1000 and 1001, since their parent is 100.
[Update]
So there remain these questions:
Do you just need the nodes ordered so that each node is defined somewhere before it is used as a parent?
Do the direct children have to follow their parent directly, oder may there be some other nodes in between?
Is the parent ID always smaller than the node ID?
Maybe you're looking at a way to make a flat array have some sort of hierarchie?
This is a very simple case which will do that asuming your children always have a higher id than their parent.
<?php
$array = array(
'354' => array(
'parent' => 0
),
'370' => array(
'parent' => 0
),
'420' => array(
'parent' => 354
),
'550' => array(
'parent' => 420
),
);
/**
*
* This function will convert a flat array with elements to the proper hierarchy structure
* #param array $array
*/
function hierarchy(&$array) {
arsort($array);
foreach($array as $key => $value)
{
if($value['parent'])
{
$array[$value['parent']]['children'][$key] = $value;
unset($array[$key]);
}
}
asort($array);
return $array;
}
(print '<pre>' . print_r(hierarchy($array), true) . '</pre>');
Heres a testcase:
http://codepad.org/RT51uOfn