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.
Related
I have an array which have string kind of object I can say
Array
(
[0] => Name=xyz
[1] => Email=xyz43#gmail.com
[2] => Password=xyz#123
[3] => Address=xyz University Lucknow
[4] => City=xyz
[5] => Name=peter
[6] => Email=peter43#gmail.com
[7] => Password=peter#123
[8] => Address=address
[9] => City=bla
[10] => Name=Jack
[11] => Email=jack76#gmail.com
[12] => Password=jack123
[13] => Address=jackAddress
[14] => City=jackCity
)
desired output
Array
(
[Email] => xyz43#gmail.com
[Email] => peter43#gmail.com
[Email] => jack76#gmail.com
[Password] =>xyz#123
[Password] =>peter#123
[Password] =>jack123
)
Let me confess that I want this stuff for login purpose thank you in advance .
You can try like this
$stringArray = ['Name=xyz','Email=xyz43#gmail.com','Password=xyz#123','Address=xyz University Lucknow','Name=xyz','Email=xyz413#gmail.com','Password=xyz1#123','Address=xyz University Lucknow'];
$loginCredentials = [];
$i = 0;
foreach($stringArray as $item){
$data = explode('=', $item);
if(in_array('Email',$data) || in_array('Password',$data)){
$loginCredentials[$i][$data[0]] = $data[1];
if(isset($loginCredentials[$i]['Email']) && isset($loginCredentials[$i]['Password'])){
$i++;
}
}
}
//Output desired array
print_r($loginCredentials);
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();
}
I have this code:
And this is my data structure:
totalMes Function:
function totalMes(){
//Genera un array con el total de cada mes
global $tickets;
$totales = ["juego" => '', "precioTicket" => 0, "cantidadTickets" => 0];
for ($i=0; $i < 12; $i++) {
foreach($tickets[$i] as $juegos){
foreach ($juegos as $key => $value){
$totales[$key] += $value;
$totalMes[$i] = $totales['precioTicket'] * $totales['cantidadTickets'];
}
$totales = ["juego" => '', "precioTicket" => 0, "cantidadTickets" => 0];
}
}
return $totalMes;
}
Now when I enter a new value to array tickets and then I call totalMes function. It accumulates me only the last value of the array tickets.
Example:
function ingresarJuego($mes, $juego, $precioTicket, $cantidadTickets){
global $tickets;
$juego = ["juego" => $juego, "precioTicket" => $precioTicket, "cantidadTickets" => $cantidadTickets];
array_push($tickets[$mes], $juego);
return $tickets;
}
This is my array totalMes, before entering a new record to array tickets:
Array
(
[0] => 100
[1] => 1886
[2] => 774
[3] => 720
[4] => 7719
[5] => 5238
[6] => 2430
[7] => 2736
[8] => 1080
[9] => 315
[10] => 621
[11] => 6536
)
Now if I enter a value in array tickets and then calculate totalMes again. it does not accumulate the values if the treads with the last record.
Array
(
[0] => 4 // When it should be 100 + 4
[1] => 1886
[2] => 774
[3] => 720
[4] => 7719
[5] => 5238
[6] => 2430
[7] => 2736
[8] => 1080
[9] => 315
[10] => 621
[11] => 6536
)
I don't understand well your questio but
Could be you need and add for the value
array_push($tickets[$mes],$tickets[$mes] + $juego);
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);
?>
This is what my array looks like :
Array (
[0] => SimpleXMLElement Object (
[key] => Array (
[0] => Track ID
[1] => Name
[2] => Artist
[3] => Album Artist
[4] => Composer
[5] => Album
[6] => Genre
[7] => Kind
[8] => Size
[9] => Total Time
[10] => Disc Number
[11] => Disc Count
[12] => Track Number
[13] => Year
[14] => Date Modified
[15] => Date Added
[16] => Bit Rate
[17] => Sample Rate
[18] => Play Count
[19] => Play Date
[20] => Play Date UTC
[21] => Artwork Count
[22] => Persistent ID
[23] => Track Type
[24] => Location
[25] => File Folder Count
[26] => Library Folder Count )
[integer] => Array (
[0] => 2056
[1] => 3732918
[2] => 230661
[3] => 1
[4] => 1
[5] => 1
[6] => 1993
[7] => 128
[8] => 44100
[9] => 3
[10] => 3439412487
[11] => 1
[12] => 5
[13] => 1 )
[string] => Array (
[0] => Eye of the Tiger
[1] => Survivor
[2] => Survivor
[3] => Frankie Sullivan/Jim Peterik
[4] => Greatest Hits
[5] => Rock
[6] => MPEG audio file
[7] => 772F0F53F195E705
[8] => File
[9] => file://localhost/Users/cameron/Music/iTunes/iTunes%20Media/Music/Survivor/Greatest%20Hits/01%20Eye%20of%20the%20Tiger.mp3 )
[date] => Array (
[0] => 2012-08-27T17:01:00Z
[1] => 2012-08-27T17:01:03Z
[2] => 2012-12-27T07:21:27Z ) )
that's 1 result, there is about 50 of them repeated.
I am trying to select the artist value in this case : Frankie Sullivan/Jim Peterik
please note: there is about 50 other results that come after this first one, so I would like to do a foreach to display all results.
any suggestions? I am stuck.this is the code I used to get these results:
$xml = simplexml_load_file('Library.xml');
$xmlx = $xml->dict->dict->dict->key;
$artist = $xmlx->xpath("//dict[key='Artist']");
echo "<pre>" . print_r($artist, true) . "</pre>";
It seems that you have an array of SimpleXMLElement,
so you can iterate over your array and use the SimpleXMLElement facilities.
Try:
foreach($yourArray as $simpleXmlElement)
{
// Retrieve the name
echo $simpleXmlElement->string[3];
}
Take a look at the documentation for more question: SimpleXMLElement
For your specific problem, assuming the key and string are synchronized, you can try:
// Loop on your array of SimpleXMLElement
foreach($yourArray as $simpleXmlElement)
{
// Initialize the position and found value
$position = 0;
$found = false;
// Loop on the sub array 'key' and search the 'Artist Album' position
foreach($simpleXmlElement->key as $index => $value)
{
if ($value == "Album Artist")
{
$found = true;
break;
}
// Not found, increment position
$position++;
}
// Retrieve the name if found the artist album key
if ($found)
echo $simpleXmlElement->string[$position];
}
As
[3] => Album Artist
will give the position 3
Then, when retrieving the string value, it will return Frankie Sullivan/Jim Peterik