Filtering large array from SQL result - php

I have an SQL query that returns 14 rows per userID.
It pulls a lot of data to verify different fields, but specifically returned I need the first and last name. The first name I can get from $firstName[]=$row2[0]; but I can't get the last name value out of the array. I can see its position, but I'm not sure how to call that position in the loop.
echo '<table border=1><tr><td>Student ID</td><td>Full Name</td><td>Class</td></tr>';
//Build Student Info1 table
foreach($userID as $val) {
$user_id= $val;
$query="SELECT * FROM wp_usermeta WHERE meta_key ='purchased_instances' AND user_id ='$user_id'";
$query2="SELECT meta_value FROM wp_usermeta WHERE user_id ='$user_id'";
$result = $link->query($query)or die($link->error);
$result2 = $link->query($query2)or die($link->error);
if($result->num_rows > 0){
/* fetch associative array */
$i=0;
while ($row = mysqli_fetch_array($result)) {
while($row2 = mysqli_fetch_array($result2)) {
$details[$i][]=$row2;
$firstName[]=$row2[0];
$lastName[]=$row2[0]; //Can't get this value right, need the first element of the 2 indexed array
}
$result1[]=$row;
$studentID[$i]=$row[1];
$classDetails[$i]=$row[3];
echo'<tr><td>';
print_r($studentID[$i]);
echo '</td><td>';
print_r($firstName[$i]);
echo ' ';
print_r($lastName[$i]);
echo'</td><td>';
print_r($classDetails[$i]);
echo '</td></tr>';
$i++;
}
/* free result set */
mysqli_free_result($result);
}
}
echo '</table>';
This is what print_r($details) produces:
Array ( [0] => Array ( [0] => 2567 [umeta_id] => 2567 [1] => 185 [user_id] => 185 [2] => first_name [meta_key] => first_name [3] => Kevin [meta_value] => Kevin ) [1] => Array ( [0] => 2568 [umeta_id] => 2568 [1] => 185 [user_id] => 185 [2] => last_name [meta_key] => last_name [3] => RealLastNameHERE [meta_value] => RealLastNameHERE ) [2] => Array ( [0] => 2569 [umeta_id] => 2569 [1] => 185 [user_id] => 185 [2] => nickname [meta_key] => nickname [3] => KMOwner [meta_value] => KMOwner ) [3] => Array ( [0] => 2570 [umeta_id] => 2570 [1] => 185 [user_id] => 185 [2] => description [meta_key] => description [3] => [meta_value] => ) [4] => Array ( [0] => 2571 [umeta_id] => 2571 [1] => 185 [user_id] => 185 [2] => rich_editing [meta_key] => rich_editing [3] => true [meta_value] => true ) [5] => Array ( [0] => 2572 [umeta_id] => 2572 [1] => 185 [user_id] => 185 [2] => comment_shortcuts [meta_key] => comment_shortcuts [3] => false [meta_value] => false ) [6] => Array ( [0] => 2573 [umeta_id] => 2573 [1] => 185 [user_id] => 185 [2] => admin_color [meta_key] => admin_color [3] => fresh [meta_value] => fresh ) [7] => Array ( [0] => 2574 [umeta_id] => 2574 [1] => 185 [user_id] => 185 [2] => use_ssl [meta_key] => use_ssl [3] => 0 [meta_value] => 0 ) [8] => Array ( [0] => 2575 [umeta_id] => 2575 [1] => 185 [user_id] => 185 [2] => show_admin_bar_front [meta_key] => show_admin_bar_front [3] => true [meta_value] => true ) [9] => Array ( [0] => 2576 [umeta_id] => 2576 [1] => 185 [user_id] => 185 [2] => wp_capabilities [meta_key] => wp_capabilities [3] => a:1:{s:10:"subscriber";b:1;} [meta_value] => a:1:{s:10:"subscriber";b:1;} ) [10] => Array ( [0] => 2577 [umeta_id] => 2577 [1] => 185 [user_id] => 185 [2] => wp_user_level [meta_key] => wp_user_level [3] => 0 [meta_value] => 0 ) [11] => Array ( [0] => 2578 [umeta_id] => 2578 [1] => 185 [user_id] => 185 [2] => mgm_member_options [meta_key] => mgm_member_options [3] => a:35:{s:2:"id";i:185;s:13:"custom_fields";a:6:{s:10:"first_name";s:5:"Kevin";s:9:"last_name";s:13:"RealLastNameHERE";s:5:"email";s:23:"RealEmailAddressHERE";s:8:"username";s:7:"RealuserNameHERE";s:8:"password";s:16:"Lwp9E8RZECyB9bzb";s:13:"password_conf";N;}s:22:"other_membership_types";a:0:{}s:12:"payment_info";a:0:{}s:6:"coupon";a:2:{s:12:"update_usage";b:0;s:15:"coupon_usage_id";b:0;}s:7:"upgrade";a:1:{s:6:"coupon";a:0:{}}s:6:"extend";a:0:{}s:4:"code";s:10:"mgm_member";s:4:"name";s:10:"Member Lib";s:11:"description";s:10:"Member Lib";s:7:"setting";a:0:{}s:6:"saving";b:1;s:8:"trial_on";i:0;s:10:"trial_cost";d:0;s:14:"trial_duration";i:0;s:19:"trial_duration_type";s:1:"d";s:16:"trial_num_cycles";i:0;s:8:"duration";i:1;s:13:"duration_type";s:1:"l";s:6:"amount";d:0;s:8:"currency";s:3:"USD";s:9:"join_date";i:1383183050;s:13:"last_pay_date";s:0:"";s:11:"expire_date";s:0:"";s:15:"membership_type";s:4:"free";s:6:"status";s:6:"Active";s:12:"payment_type";s:0:"";s:13:"autoresponder";s:10:"mgm_aweber";s:10:"subscribed";s:1:"Y";s:22:"autoresponder_notified";s:1:"Y";s:13:"user_password";s:16:"Lwp9E8RZECyB9bzb";s:17:"active_num_cycles";i:1;s:7:"pack_id";s:2:"22";s:12:"account_desc";s:12:"Free Account";s:16:"hide_old_content";s:1:"0";} [meta_value] => a:35:{s:2:"id";i:185;s:13:"custom_fields";a:6:{s:10:"first_name";s:5:"Kevin";s:9:"last_name";s:13:"RealLastNameHERE";s:5:"email";s:23:"RealuserNameHERE";s:8:"username";s:7:"RealuserNameHERE";s:8:"password";s:16:"Lwp9E8RZECyB9bzb";s:13:"password_conf";N;}s:22:"other_membership_types";a:0:{}s:12:"payment_info";a:0:{}s:6:"coupon";a:2:{s:12:"update_usage";b:0;s:15:"coupon_usage_id";b:0;}s:7:"upgrade";a:1:{s:6:"coupon";a:0:{}}s:6:"extend";a:0:{}s:4:"code";s:10:"mgm_member";s:4:"name";s:10:"Member Lib";s:11:"description";s:10:"Member Lib";s:7:"setting";a:0:{}s:6:"saving";b:1;s:8:"trial_on";i:0;s:10:"trial_cost";d:0;s:14:"trial_duration";i:0;s:19:"trial_duration_type";s:1:"d";s:16:"trial_num_cycles";i:0;s:8:"duration";i:1;s:13:"duration_type";s:1:"l";s:6:"amount";d:0;s:8:"currency";s:3:"USD";s:9:"join_date";i:1383183050;s:13:"last_pay_date";s:0:"";s:11:"expire_date";s:0:"";s:15:"membership_type";s:4:"free";s:6:"status";s:6:"Active";s:12:"payment_type";s:0:"";s:13:"autoresponder";s:10:"mgm_aweber";s:10:"subscribed";s:1:"Y";s:22:"autoresponder_notified";s:1:"Y";s:13:"user_password";s:16:"Lwp9E8RZECyB9bzb";s:17:"active_num_cycles";i:1;s:7:"pack_id";s:2:"22";s:12:"account_desc";s:12:"Free Account";s:16:"hide_old_content";s:1:"0";} ) [12] => Array ( [0] => 2579 [umeta_id] => 2579 [1] => 185 [user_id] => 185 [2] => _wpsc_customer_profile [meta_key] => _wpsc_customer_profile [3] => a:5:{s:16:"shipping_country";s:2:"US";s:15:"billing_country";s:2:"US";s:15:"shipping_region";s:2:"22";s:14:"billing_region";s:2:"22";s:4:"cart";s:1056:"O:9:"wpsc_cart":37:{s:16:"delivery_country";s:2:"US";s:16:"selected_country";s:2:"US";s:15:"delivery_region";s:2:"22";s:15:"selected_region";s:2:"22";s:24:"selected_shipping_method";N;s:24:"selected_shipping_option";N;s:24:"selected_shipping_amount";N;s:6:"coupon";N;s:14:"tax_percentage";N;s:9:"unique_id";s:40:"905310a45d51d75129b9de961ae17f69a7129ced";s:6:"errors";a:0:{}s:9:"total_tax";N;s:13:"base_shipping";N;s:19:"total_item_shipping";N;s:14:"total_shipping";N;s:8:"subtotal";N;s:11:"total_price";N;s:13:"uses_shipping";N;s:13:"is_incomplete";b:1;s:10:"cart_items";a:0:{}s:9:"cart_item";N;s:15:"cart_item_count";i:0;s:17:"current_cart_item";i:-1;s:11:"in_the_loop";b:0;s:16:"shipping_methods";b:0;s:15:"shipping_method";N;s:21:"shipping_method_count";i:1;s:23:"current_shipping_method";i:-1;s:18:"in_the_method_loop";b:0;s:15:"shipping_quotes";a:0:{}s:14:"shipping_quote";N;s:20:"shipping_quote_count";i:0;s:22:"current_shipping_quote";i:-1;s:17:"in_the_quote_loop";b:0;s:12:"coupons_name";s:0:"";s:14:"coupons_amount";i:0;s:15:"shipping_option";N;}";} [meta_value] => a:5:{s:16:"shipping_country";s:2:"US";s:15:"billing_country";s:2:"US";s:15:"shipping_region";s:2:"22";s:14:"billing_region";s:2:"22";s:4:"cart";s:1056:"O:9:"wpsc_cart":37:{s:16:"delivery_country";s:2:"US";s:16:"selected_country";s:2:"US";s:15:"delivery_region";s:2:"22";s:15:"selected_region";s:2:"22";s:24:"selected_shipping_method";N;s:24:"selected_shipping_option";N;s:24:"selected_shipping_amount";N;s:6:"coupon";N;s:14:"tax_percentage";N;s:9:"unique_id";s:40:"905310a45d51d75129b9de961ae17f69a7129ced";s:6:"errors";a:0:{}s:9:"total_tax";N;s:13:"base_shipping";N;s:19:"total_item_shipping";N;s:14:"total_shipping";N;s:8:"subtotal";N;s:11:"total_price";N;s:13:"uses_shipping";N;s:13:"is_incomplete";b:1;s:10:"cart_items";a:0:{}s:9:"cart_item";N;s:15:"cart_item_count";i:0;s:17:"current_cart_item";i:-1;s:11:"in_the_loop";b:0;s:16:"shipping_methods";b:0;s:15:"shipping_method";N;s:21:"shipping_method_count";i:1;s:23:"current_shipping_method";i:-1;s:18:"in_the_method_loop";b:0;s:15:"shipping_quotes";a:0:{}s:14:"shipping_quote";N;s:20:"shipping_quote_count";i:0;s:22:"current_shipping_quote";i:-1;s:17:"in_the_quote_loop";b:0;s:12:"coupons_name";s:0:"";s:14:"coupons_amount";i:0;s:15:"shipping_option";N;}";} ) [13] => Array ( [0] => 2580 [umeta_id] => 2580 [1] => 185 [user_id] => 185 [2] => purchased_instances [meta_key] => purchased_instances [3] => Cardio Stretch/Flex on 11/04/2013 8:00 AM [meta_value] => Cardio Stretch/Flex on 11/04/2013 8:00 AM )
==============================================================================
New working code:
echo '<table border=1><tr><td>Full Name</td><td>Class Purchased</td></tr>';
//Build Student Info1 table
foreach($userID as $val) {
$user_id= $val;
$queryA="SELECT meta_value FROM wp_usermeta WHERE meta_key ='first_name' AND user_id ='$user_id'";
$queryB="SELECT meta_value FROM wp_usermeta WHERE meta_key ='last_name' AND user_id ='$user_id'";
$queryC="SELECT meta_value FROM wp_usermeta WHERE meta_key ='purchased_instances' AND user_id ='$user_id'";
$resultA = $link->query($queryA)or die($link->error);
$resultB = $link->query($queryB)or die($link->error);
$resultC = $link->query($queryC)or die($link->error);
$numPurchases = $resultC->num_rows;
if($numPurchases > 0){
$i=0;
foreach($resultA as $val){
$fName[$i]=$val['meta_value'];;
$i++;
}
$i=0;
foreach($resultB as $val){
$lName[$i]=$val['meta_value'];
$i++;
}
$i=0;
foreach($resultC as $val){
$classDetails[$i]=$val['meta_value'];
$i++;
}
for($i=0; $i < $numPurchases; $i++){
echo '<td>';
print_r($fName[$i]);
echo ' ';
print_r($lName[$i]);
echo '</td><td>';
print_r($classDetails[$i]);
echo '</td></tr>';
}
/* free result set */
mysqli_free_result($resultA);
mysqli_free_result($resultB);
mysqli_free_result($resultC);
}
}
echo '';

Some important notes:
Validate any user input
NEVER execute SQL in a loop
Use one query that fetches everything you need (you're using the same table)
Fetch an associative array, this will help you a lot
Specify exactly what you need in your projection (not * after SELECT, exactly state each field to fetch like SELECT foo, bar, …)
Here is some code to help you get started with the above tips:
<?php
// Validate input, please note that prepared statements would be best.
// Also note that we don't need mysql escape calls because we validate
// that this is an actual integer value which can't contain anything
// dangerous. If we'd be working with any kind of string, date, ... the
// world would look different.
if (!is_array($userID)) {
if (!is_int($userID)) {
throw new \RuntimeException;
}
$userIds = "= {$userID}";
}
else {
$userIds = null;
$c = count($userID);
for ($i = 0; $i < $c; ++$i) {
if (!is_int($userID[$i])) {
throw new \RuntimeException;
}
$userIds .= $userIds ? "," : "IN(";
$userIds .= $userID[$i];
}
$userIds .= ")";
}
// One query to rule them all and nice formatting for readability.
$result = $link->query(
"SELECT *
FROM `wp_usermeta`
WHERE `meta_key` = 'purchased_instances'
AND `user_id` {$userIds}"
);
// Now we fetch everything within a single loop.
while ($row = mysqli_fetch_assoc($result)) {
print_r($row);
}
// That's it!
mysqli_free_result($result);
?>

Related

Get Data from database using array values with for loop in PHP

Array:
$ecodesAr = Array (
[0] => 1Z0-060
[1] => 98-375
[2] => 98-368
[3] => 98-367 )
for($k=0; $k<count($ecodesAr); $k++){
$arrayTB[$k] = $this->Functions->exam('title', $ecodesAr[$k]); }
Modal code:
public function exam($q, $d) {
$q = $this->db->where($q, $d)
->get('exams');
return $q->row();
}
Result:
Array (
[0] =>
[1] =>
[2] =>
[3] => stdClass Object ( [id] => 1091 [hot_exam] => 0 [top_exam] => 0 [category] => 114 [subcats] => 288 [slug] => 98-367 [sku] => OI5Ao [title] => 98-367 [name] => MTA Security Fundamentals [update] => 2021-09-16 [regular_price] => 130 [sale_price] => 59 [on_homepage] => 0 [on_request] => 0 [expired] => 0 [path_slug] => 98-367.pdf [questions] => 123 [demo_slug] => 98-367-demo.pdf [prc_price] => 65 [prc_demo] => 98-367-demo [prc_exam] => 98-367 [is_active] => 1 )
)
The First 3 values are skiped in the output and just the last value got, I want to all array data against values please help anyone!
$productsarry = Array (
[0] => Milk
[1] => Cream
[2] => Sugar
[3] => Yougert
);
for($k = 0; $k < count($productsarry); $k++) {
$arrayTB[$k] = query("select slug, qty, name, price from exams where title ='$ecode'")->row();
}

Array and Mysql insert using PDO

0I have an array ($dataArray) in the following format which is created from a csv file:
The CSV is processed as follows:
function csvstring_to_array($string, $separatorChar = ',', $enclosureChar = '"', $newlineChar = "\n") {
// #author: Klemen Nagode
$array = array();
$size = strlen($string);
$columnIndex = 0;
$rowIndex = 0;
$fieldValue="";
$isEnclosured = false;
for($i=0; $i<$size;$i++) {
$char = $string{$i};
$addChar = "";
if($isEnclosured) {
if($char==$enclosureChar) {
if($i+1<$size && $string{$i+1}==$enclosureChar){
// escaped char
$addChar=$char;
$i++; // dont check next char
}else{
$isEnclosured = false;
}
}else {
$addChar=$char;
}
}else {
if($char==$enclosureChar) {
$isEnclosured = true;
}else {
if($char==$separatorChar) {
$array[$rowIndex][$columnIndex] = $fieldValue;
$fieldValue="";
$columnIndex++;
}elseif($char==$newlineChar) {
echo $char;
$array[$rowIndex][$columnIndex] = $fieldValue;
$fieldValue="";
$columnIndex=0;
$rowIndex++;
}else {
$addChar=$char;
}
}
}
if($addChar!=""){
$fieldValue.=$addChar;
}
}
if($fieldValue) { // save last field
$array[$rowIndex][$columnIndex] = $fieldValue;
}
return $array;
}
$dataArray = csvstring_to_array( file_get_contents("ACS_MONTHLY_DUES - Jun 2020.csv"));
echo '<pre>';
print_r($dataArray);
echo '</pre>';
Array
(
[0] => Array
(
[0] => REGION
[1] => CENTER
[2] => SUBSCRIBER CODE
[3] => SUBSCRIBER_ID
[4] => SUBSCRIBERNAME
[5] => SUBSCRIBERPHONE
[6] => BOUQ
[7] => STB_NOS
[8] => LAST MONTH PAYMENT
[9] => AMOUNT_DUE
[10] => MINIMUM_RECHARGE
[11] => TOTAL_PAYABLE
[12] => EXPIRY_DATE
[13] => PAY_AMOUNT
[14] => CURRENT BALANCE
)
[1] => Array
(
[0] => XXX
[1] => XXX
[2] => UK91002970
[3] => 61610070
[4] => XXXXX
[5] => XXXXXX
[6] => UK FTA-1
[7] => 1
[8] => 0
[9] => 0
[10] => 221
[11] => 221
[12] => 08-06-2020
[13] => 0
[14] => 0
)
[2] => Array
(
[0] => XXXX
[1] => XXXXX
[2] => UK91002971
[3] => 61610217
[4] => XXXXXXX
[5] => XXXXXXX
[6] => UK FTA-1
[7] => 1
[8] => 0
[9] => 8
[10] => 243
[11] => 251
[12] => 06-06-2020
[13] => 0
[14] => 0
)
)
I need to insert it in my mysql DB using PDO. I tried the following and it is not working:
include_once('inc/connstring.inc.php');
$stmt = $conn->prepare("INSERT INTO customer(subscriber_code, subscriber_id, region,center,subscriber_name,subscriber_phone,package,stb_nos,last_month_payment,amount_due,minimum_recharge,total_payable,expiry_date,pay_amount,current_balance)
VALUES(:subscribercode, :subscriberid, :region,:center,:subscribername,:subscriberphone,:package,:stbnos,:lastmonthpayment,:amountdue,:minimumrecharge,:totalpayable,:expirydate,:payamount,:currentbalance)");
foreach($dataArray as $row) {
$stmt->execute(array(
':subscribercode' => $row['SUBSCRIBER CODE'],
':subscriberid' => $row['SUBSCRIBER_ID'],
':region' => $row['REGION'],
':center' => $row['CENTER'],
':subscribername' => $row['SUBSCRIBERNAME'],
':subscriberphone' => $row['SUBSCRIBERPHONE'],
':package' => $row['BOUQ'],
':stbnos' => $row['STB_NOS'],
':lastmonthpayment' => $row['LAST MONTH PAYMENT'],
':amountdue' => $row['AMOUNT_DUE'],
':minimumrecharge' =>$row['MINIMUM_RECHARGE'],
':totalpayable' => $row['TOTAL_PAYABLE'],
':expirydate' => $row['EXPIRY_DATE'],
':payamount' => $row['PAY_AMOUNT'],
':currentbalance' => $row['CURRENT BALANCE']));
}
It is not working. Invalid argument supplied for foreach()
What am i doing wrong?? Requesting help from php experts...
Thanks in advance.
update:
Solved myself. Changed code to convert CSV to an associative array and now everything works fine.
Array
(
[0] => Array
(
[REGION] => XXX
[CENTER] => XXXXX
[SUBSCRIBER CODE] =>UK91002970
[SUBSCRIBER_ID] => 61610070
[SUBSCRIBERNAME] => XXXXX
[SUBSCRIBERPHONE] => XXXXXXX
[BOUQ] => UK FTA-1
[STB_NOS] => 1
[LAST MONTH PAYMENT] => 0
[AMOUNT_DUE] => 0
[MINIMUM_RECHARGE] => 221
[TOTAL_PAYABLE] => 221
[EXPIRY_DATE] => 08-06-2020
[PAY_AMOUNT] => 0
[CURRENT BALANCE] => 0
)
Your array $dataArray contains this:
Array
(
[0] => Array
(
[0] => REGION
[1] => CENTER
[2] => SUBSCRIBER CODE
[3] => SUBSCRIBER_ID
[4] => SUBSCRIBERNAME
[5] => SUBSCRIBERPHONE
[6] => BOUQ
[7] => STB_NOS
[8] => LAST MONTH PAYMENT
[9] => AMOUNT_DUE
[10] => MINIMUM_RECHARGE
[11] => TOTAL_PAYABLE
[12] => EXPIRY_DATE
[13] => PAY_AMOUNT
[14] => CURRENT BALANCE
)
[1] => Array
(
[0] => XXX
[1] => XXX
[2] => UK91002970
[3] => 61610070
[4] => XXXXX
[5] => XXXXXX
[6] => UK FTA-1
[7] => 1
[8] => 0
[9] => 0
[10] => 221
[11] => 221
[12] => 08-06-2020
[13] => 0
[14] => 0
)
You try to apply values values into your SQL by using REGION, CENTER, SUBSRICBER CODE etc. but you're mixing up keys with values
This array does not include $row['REGION'], does not include $row['CENTER'] etc...
If you're doing like this:
foreach($dataArray as $row) {
$stmt->execute(array(
':subscribercode' => $row['SUBSCRIBER CODE'],
':subscriberid' => $row['SUBSCRIBER_ID'],
etc...
}
then the array $dataArray would have to look like this:
Array
(
['SUBSCRIBER CODE'] => {value}
['SUBSCRIBER_ID'] => {value}
['SUBSCRIBERNAME'] => {value}
etc
)
One solution would be if (if I understand the array structure correctly) to apply keys from second and further based on first elements values
Lets say we have this:
Array
(
[0] => Array
(
[0] => REGION
[1] => CENTER
[2] => SUBSCRIBER CODE
[3] => SUBSCRIBER_ID
)
[1] => Array
(
[0] => XXX
[1] => XXX
[2] => UK91002970
[3] => 61610070
)
[2] => Array
(
[0] => XXX
[1] => XXX
[2] => UK91002971
[3] => 61610217
)
[3] => Array
(
[0] => XXX
[1] => XXX
[2] => UK91002972
[3] => 61610218
)
)
then first element contains: ['REGION', 'CENTER', 'SUBSCRIBER CODE','SUBSCRIBER_ID']
and second to fourth element contains the actual values "mapped to region, center , subscriber code, subscriber id".
A solution would be:
$dataArray = [];
$dataArray[] = ['REGION', 'CENTER', 'SUBSCRIBER CODE','SUBSCRIBER_ID'];
$dataArray[] = ['XXX', 'XXX', 'UK91002970', '61610070'];
$dataArray[] = ['XXX', 'XXX', 'UK91002971', '61610217'];
$dataArray[] = ['XXX', 'XXX', 'UK91002972', '61610218'];
$keys_apply = array_values($dataArray[0]); //get all values of first item in array
$i = 0;
foreach($dataArray as $key=>$item) {
if ($i>0) { //skip first item
$index = 0; //We know that index are 0 and above we start with zero here and
//and add one for each iteration
foreach($item as &$ik) {
//create new item with mapped key-value from first item in array but with
//the same value ($ik)
$dataArray[$key][$keys_apply[$index]] = $ik;
//Unset removes $dataArray[1][0], [1][1], [1][2] etc.
unset($dataArray[$key][$index]);
//Next element in this inner array
$index++;
}
}
$i++;
}
You would then have:
Array
(
[0] => Array
(
[0] => REGION
[1] => CENTER
[2] => SUBSCRIBER CODE
[3] => SUBSCRIBER_ID
)
[1] => Array
(
[REGION] => XXX
[CENTER] => XXX
[SUBSCRIBER CODE] => UK91002970
[SUBSCRIBER_ID] => 61610070
)
[2] => Array
(
[REGION] => XXX
[CENTER] => XXX
[SUBSCRIBER CODE] => UK91002971
[SUBSCRIBER_ID] => 61610217
)
[3] => Array
(
[REGION] => XXX
[CENTER] => XXX
[SUBSCRIBER CODE] => UK91002972
[SUBSCRIBER_ID] => 61610218
)
)
And then your original
foreach($dataArray as $row) {
$stmt->execute(array(
':subscribercode' => $row['SUBSCRIBER CODE'],
etc...
}
would work.

connect arrays into one

How i can transform this first array [ONE}: Into second array [TWO} where i can call meta_key and than i get var: i get this array by calling specified sql rows and i am using this query: $user_data = $wpdb->get_results("SELECT * FROM $wpdb->usermeta WHERE user_id = $fivesdraft->user_id "); maybe its another better way to connect it in query? not in PHP
Array ONE
(
[0] => stdClass Object
(
[umeta_id] => 16
[user_id] => 2
[meta_key] => nickname
[meta_value] => user1
)
[1] => stdClass Object
(
[umeta_id] => 17
[user_id] => 2
[meta_key] => first_name
[meta_value] => testname
)
[2] => stdClass Object
(
[umeta_id] => 18
[user_id] => 2
[meta_key] => last_name
[meta_value] => testlastname
)
[3] => stdClass Object
(
[umeta_id] => 19
[user_id] => 2
[meta_key] => description
[meta_value] => user desc
)
)
Array TWO
(
[nickname] => 'user1'
[first_name] => 'user desc'
[last_name] => 'user desc'
[description] => 'user desc'
...
)
You can use array_reduce:
$myArray = array_reduce($arrayOne, function ($result, $item) {
$result[$item->meta_key] = $item->meta_value;
return $result;
}, array());
Just loop over the array and write the values in a new array
$two = array();
foreach ($one as $item) {
$two[$item->meta_key] = $item->meta_value;
}

Creating a multidimensional array using an array and loop through mysql table

I have a table with the following structure. There are currently 9 students enrolled in 3 classes (classes 01, 16 and 52), with 3 enrollments in each class.
studentcode | classcode
-------------------------
D3kcIvyp | 01
DdIhBc | 01
2vx0KV | 01
9p1PxWCV | 52
RnmfH1WE | 52
MSTBEv | 52
Yp4J3o | 16
fWQ5Oo | 16
6sxw3u | 16
This is the array with all current classes:
$classes_array = array ( [0] => 01 [1] => 52 [2] => 16 )
Using this array I would like to go through the mysql table and create a multidimensional array with the classcodes used as first level keys:
Array
(
[01] => Array
(
[0] => D3kcIvyp
[1] => DdIhBc
[2] => 2vx0KV
)
[52] => Array
(
[0] => 9p1PxWCV
[1] => RnmfH1WE
[2] => MSTBEv
)
[16] => Array
(
[0] => Yp4J3o
[1] => fWQ5Oo
[2] => 6sxw3u
)
)
foreach ($classes_array as $key => $value)
{
$sql = "SELECT studentcode FROM table WHERE classcode = '$classes_array[$key]'";
$result = mysql_query($sql) or die();
while($data = mysql_fetch_array($result))
{
$studentcodes_array[] = $data['studentcode'];
}
foreach ($studentcodes_array as $studentcodeskey => $studentcodesvalue)
{
$multid_array[$value][] = $studentcodesvalue;
}
}
Using the code above, unfortunately I don't get the array I would like to get. I get this instead:
Array
(
[01] => Array
(
[0] => D3kcIvyp
[1] => DdIhBc
[2] => 2vx0KV
)
[52] => Array
(
[0] => D3kcIvyp
[1] => DdIhBc
[2] => 2vx0KV
[3] => 9p1PxWCV
[4] => RnmfH1WE
[5] => MSTBEv
)
[16] => Array
(
[0] => D3kcIvyp
[1] => DdIhBc
[2] => 2vx0KV
[3] => 9p1PxWCV
[4] => RnmfH1WE
[5] => MSTBEv
[6] => Yp4J3o
[7] => fWQ5Oo
[8] => 6sxw3u
)
)
What is wrong with my code? Can anybody help me with this?
You never initialise $studentcodes_array so it is remembering all the values from your previous loops.
Try adding $studentcodes_array = array(); before your while.

How to group elements of array using Primary and secondary key?

I've got this array:
Array
(
[0] => Array
(
[id]=>1
[account_id] => 1
[object_id] => 43
[object_type] => PHOTO
[action_type] => UPLOAD_PHOTO
)
[1] => Array
(
[id] => 1
[account_id] => 1
[object_id] => 42
[object_type] => PHOTO
[action_type] => UPLOAD_PHOTO
)
[2] => Array
(
[id] => 1
[account_id] => 1
[object_id] => 41
[object_type] => PHOTO
[action_type] => UPLOAD_PHOTO
)
[3] => Array
(
[id] => 2
[account_id] => 2
[object_id] => 1
[object_type] => USER
[action_type] => FOLLOW_USER
)
[4] => Array
(
[id] => 1
[account_id] => 1
[object_id] => 2
[object_type] => USER
[action_type] => FOLLOW_USER
)
[5] => Array
(
[id] => 1
[account_id] => 1
[object_id] => 1
[object_type] => PHOTO
[action_type] => UPLOAD_PHOTO
)
)
Now I want to group elements have same value (for example UPLOAD_PHOTO) by id as Primary Key and action_type as Secondary Key, like:
Array
(
[0] => Array(
[id] => 1
[account_id] => 1
[actions] => array(
[1] => array(
[object_id] => 42
[object_type] => PHOTO
[action_type] => UPLOAD_PHOTO
)
[2] => array(
[object_id] => 43
[object_type] => PHOTO
[action_type] => UPLOAD_PHOTO
)
)
)
[2] => Array
(
[id] => 1
[account_id] => 1
[actions] = array(
[0] => Array
(
[object_id] => 3
[object_type] => USER
[action_type] => FOLLOW_USER
)
[1] => Array
(
[object_id] => 4
[object_type] => USER
[action_type] => FOLLOW_USER
)
)
)
)
I tried some solutions but didn't succeed.
When constructing your output array, you'll want to use meaningful array keys. That way you can find the out element that the in element needs to be added to:
$in = (...your array...);
$out = array();
foreach($in as $element) {
$id = $element['id'];
//If that id hasn't been seen yet, create the out element.
if (!isset($out[$id])) {
$out[$id] = array(
'id'=>$element['id'],
'account_id' => $element['account_id'],
'actions' => array()
);
}
//Add that action to the out element
$out[$id]['actions'][] = array(
'object_id' => $element['object_id'],
'object_type' => $element['object_type'],
'action_type' => $element['action_type']
);
}
I'm not sure why your input elements have different fields... If this is a desired feature, where one set of possible fields belongs to the id group and another set belongs to the action, you can do this instead (slightly less readable, but more flexible):
$in = (...your array...);
$out = array();
//These define which fields from an
//input element belong to the id,
//and which to the action.
$id_fields = array_flip(array('id','account_id','object_user_id');
$action_fields = array_flip(array('object_id','object_type','action_type');
foreach($in as $element) {
$id = $element['id'];
//If that id hasn't been seen yet, create the out element.
if (!isset($out[$id])) {
$out[$id] = array_intersect_key($element, $id_fields);
$out[$id]['actions'] = array();
}
//Add that action to the out element
$out[$id]['actions'][] = array_intersect_key($element, $action_fields);
}
This is a better solution if the input elements can be different, because if an expected field (other than 'id') is missing, the script will cope with it easily.

Categories