Getting a specific id value for use - php
I'm currently working on a friendshipsystem. To accept a friend I need to get the friendship_id value.
Based on the email (from the session) I can get a lot of information, such as surname, name, photo, ID NUMBER,... from the specific friendshiprequest
I can print the information for each friendship in this way. So I have the FRIENDSHIP ID VALUE TO DISPLAY AS INFORMATION but now I want to use it in a function.
$friendrequests=$friendship->GetAllFriendRequests($email);
<?php
foreach ($friendrequests as $request) {
echo "
<div><p>
<a href='profile.php?user_id=".$request['friendship_applicant_id'] . "'>
<img src='uploads/" . $request['friendship_applicant_avatar'] . " " . " ' alt='' />" . $request['friendship_applicant_surname'] . $request['friendship_id'] . " " . $request['friendship_applicant_name'] . "
</a> has send you a friend request" . "
<form action='" . $_SERVER['REQUEST_URI'] . "' method='post'>
<button type='submit' name=''>Accept</button>
<button type='submit' name=''>Decline</button>
</form>
</p></div>";
}
?>
So i tried to get the specific number with the following code, but it says undefined index for friendship_id: $friendrequestnumber = $friendrequests['friendship_id'];
This is the code the GetAllFriendRequests function. Can I use this code or should I do it in a totally different way?
public function GetAllFriendRequests($email) {
$db = new Db();
$select = "SELECT * FROM friendship WHERE friendship_recipient = '" . $email . "' AND friendship_status = 'pending' ORDER BY friendship_id DESC";
$result = $db -> conn -> query($select);
$result_array=array();
while ($row = mysqli_fetch_array($result)) {
$result_array[]=$row;
}
return $result_array;
}
With a var_dump I get this information of the 2 requests:
Array ( [0] => Array ( [0] => 84 [friendship_id] => 84 [1] => ron#hot.com [friendship_applicant] => ron#hot.com [2] => 29 [friendship_applicant_id] => 29 [3] => ron [friendship_applicant_name] => ron [4] => ron [friendship_applicant_surname] => ron [5] => 1394134610fuckyou.jpg [friendship_applicant_avatar] => 1394134610fuckyou.jpg [6] => jan#hot.com [friendship_recipient] => jan#hot.com [7] => 1 [friendship_recipient_id] => 1 [8] => Vandenbergh [friendship_recipient_name] => Vandenbergh [9] => Jan [friendship_recipient_surname] => Jan [10] => 1394041001fuckyou.jpg [friendship_recipient_avatar] => 1394041001fuckyou.jpg [11] => Pending [friendship_status] => Pending [12] => 0000-00-00 00:00:00 [friendship_time] => 0000-00-00 00:00:00 ) [1] => Array ( [0] => 78 [friendship_id] => 78 [1] => Bert#hot.com [friendship_applicant] => Bert#hot.com [2] => 2 [friendship_applicant_id] => 2 [3] => Van Damme [friendship_applicant_name] => Van Damme [4] => Bert [friendship_applicant_surname] => Bert [5] => sdfds.png [friendship_applicant_avatar] => sdfds.png [6] => Jan#hot.com [friendship_recipient] => Jan#hot.com [7] => 1 [friendship_recipient_id] => 1 [8] => Vandenbergh [friendship_recipient_name] => Vandenbergh [9] => Jan [friendship_recipient_surname] => Jan [10] => 1394041001fuckyou.jpg [friendship_recipient_avatar] => 1394041001fuckyou.jpg [11] => Pending [friendship_status] => Pending [12] => 0000-00-00 00:00:00 [friendship_time] => 0000-00-00 00:00:00 ) )
From your var_dump, $friendrequests is a nested array. So you need to use a loop to iterate over all values like in the case above where $request['friendship_id'] can use it or if you simply want the first value, use $friendrequests[0]['friendship_id']
Related
How to access ' Json data in Laravel' [duplicate]
This question already has an answer here: How to extract and access data from JSON with PHP? (1 answer) Closed 3 years ago. I am getting the server response in json format to my laravel controller. In my controller decoding the json data and passing to my view. In laravel blade i am unable to access data. When i am printing total decoded result it is some thing like below. I tried to access this by $result->shipping_address , $result['shipping_address']. But none of them worked. JSON RESULT is like below [ {"data": { "entity_id":"77", "state":"new", "status":"pending", "coupon_code":null, "protect_code":"ab0fc2890c4c9cc93d7d4586e5dcd8ff", "shipping_description":"Flat Rate - Fixed", "is_virtual":"0", "store_id":"1", "customer_id":"2", "base_discount_amount":"0.0000", "base_discount_canceled":null, "base_discount_invoiced":null, "base_discount_refunded":null, "base_grand_total":"2146.2300", "base_shipping_amount":"5.0000", "base_shipping_canceled":null, "base_shipping_invoiced":null, "base_shipping_refunded":null, "base_shipping_tax_amount":"0.0000", "base_shipping_tax_refunded":null, "base_subtotal":"1846.6800", "base_subtotal_canceled":null, "base_subtotal_invoiced":null, "base_subtotal_refunded":null, "base_tax_amount":"294.5500", "base_tax_canceled":null, "base_tax_invoiced":null, "base_tax_refunded":null, "base_to_global_rate":"1.0000", "base_to_order_rate":"1.0000", "base_total_canceled":null, "base_total_invoiced":null, "base_total_invoiced_cost":null, "base_total_offline_refunded":null, "base_total_online_refunded":null, "base_total_paid":null, "base_total_qty_ordered":null, "base_total_refunded":null, "discount_amount":"0.0000", "discount_canceled":null, "discount_invoiced":null, "discount_refunded":null, "grand_total":"2146.2300", "shipping_amount":"5.0000", "shipping_canceled":null, "shipping_invoiced":null, "shipping_refunded":null, "shipping_tax_amount":"0.0000", "shipping_tax_refunded":null, "store_to_base_rate":"0.0000", "store_to_order_rate":"0.0000", "subtotal":"1846.6800", "subtotal_canceled":null, "subtotal_invoiced":null, "subtotal_refunded":null, "tax_amount":"294.5500", "tax_canceled":null, "tax_invoiced":null, "tax_refunded":null, "total_canceled":null, "total_invoiced":null, "total_offline_refunded":null, "total_online_refunded":null, "total_paid":null, "total_qty_ordered":"1.0000", "total_refunded":null, "can_ship_partially":null, "can_ship_partially_item":null, "customer_is_guest":"0", "customer_note_notify":"1", "billing_address_id":"76", "customer_group_id":"1", "edit_increment":null, "email_sent":null, "send_email":"1", "forced_shipment_with_invoice":null, "payment_auth_expiration":null, "quote_address_id":null, "quote_id":"72", "shipping_address_id":"75", "adjustment_negative":null, "adjustment_positive":null, "base_adjustment_negative":null, "base_adjustment_positive":null, "base_shipping_discount_amount":"0.0000", "base_subtotal_incl_tax":"2141.2300", "base_total_due":"2146.2300", "payment_authorization_amount":null, "shipping_discount_amount":"0.0000", "subtotal_incl_tax":"2141.2300", "total_due":"2146.2300", "weight":"0.0000", "customer_dob":null, "increment_id":"000000157", "applied_rule_ids":null, "base_currency_code":"INR", "customer_email":"test#gmail.com", "customer_firstname":"ridha", "customer_lastname":"Gatto", "customer_middlename":null, "customer_prefix":null, "customer_suffix":null, "customer_taxvat":null, "discount_description":null, "ext_customer_id":null, "ext_order_id":null, "global_currency_code":"INR", "hold_before_state":null, "hold_before_status":null, "order_currency_code":"INR", "original_increment_id":null, "relation_child_id":null, "relation_child_real_id":null, "relation_parent_id":null, "relation_parent_real_id":null, "remote_ip":"193.33.131.226", "shipping_method":"flatrate_flatrate", "store_currency_code":"INR", "store_name":"Main Website\nMain Website Store\n", "x_forwarded_for":null, "customer_note":null, "created_at":"2018-11-28 06:01:59", "updated_at":"2018-11-28 06:02:09", "total_item_count":"1", "customer_gender":"0", "discount_tax_compensation_amount":"0.0000", "base_discount_tax_compensation_amount":"0.0000", "shipping_discount_tax_compensation_amount":"0.0000", "base_shipping_discount_tax_compensation_amnt":"0.0000", "discount_tax_compensation_invoiced":null, "base_discount_tax_compensation_invoiced":null, "discount_tax_compensation_refunded":null, "base_discount_tax_compensation_refunded":null, "shipping_incl_tax":"5.0000", "base_shipping_incl_tax":"5.0000", "coupon_rule_name":null, "gift_message_id":null, "paypal_ipn_customer_notified":"0", "vendor_order_id":"VN100028", "extension_attributes":{ }, "items":{"50": { } } } }, { "shipping_address": { "entity_id":"75", "parent_id":"77", "customer_address_id":null, "quote_address_id":"250", "region_id":"564", "customer_id":null, "fax":null, "region":"chennai", "postcode":"700089", "lastname":"Gatto", "street":"srinaarat", "city":"chennai", "email":"test#gmail.com", "telephone":"9876543210", "country_id":"IN", "firstname":"hgd", "address_type":"shipping", "prefix":"address_","middlename":null, "suffix":null, "company":"sd", "vat_id":null, "vat_is_valid":null, "vat_request_id":null, "vat_request_date":null, "vat_request_success":null } }, { "billing_address": { "entity_id":"76", "parent_id":"77", "customer_address_id":"1", "quote_address_id":"251", "region_id":"564", "customer_id":null, "fax":null, "region":"chennai", "postcode":"700034", "lastname":"Gatt0", "street":"srinagar", "city":"chennai", "email":"text#gmail.com", "telephone":"9848352205", "country_id":"IN", "firstname":"ridha", "address_type":"billing", "prefix":null, "middlename":null, "suffix":null, "company":"ridha", "vat_id":null, "vat_is_valid":null, "vat_request_id":null, "vat_request_date":null, "vat_request_success":null } }, { "vendor": { "entity_id":"1", "entity_type_id":"9", "attribute_set_id":"0", "increment_id":"000000009", "parent_id":"0", "created_at":"2018-10-01 11:09:32", "updated_at":"2018-11-27 12:55:57", "is_active":"1", "website_id":"1", "address":"chennai", "city":"chennai", "zip_code":"700087", "customer_id":"1", "shop_url":"cf97wksk", "status":"approved", "group":"general", "public_name":"cf97wksk", "name":"test", "email":"test#gmail.com", "contact_number":"9876543210", "country_id":"IN", "vendor_gstin":"11PGTAU12346Q", "gender":"1", "region_id":"564" } }, { "items": {"item_id":"50", "order_id":"77", "parent_item_id":null, "quote_item_id":"208", "store_id":"1", "created_at":"2018-11-28 06:02:09", "updated_at":"2018-11-28 06:02:09", "product_id":"14", "product_type":"simple", "product_options": { "info_buyRequest": {"uenc":"aHR0cDovLzE1OS44OS4xNjQuMTM5L2IyYi9idXkxLWtsbS1mYXNoaW9uLW1hbGwtd29tZW4tcy1mYW5jeS1jb3R0b24tc2lsay1zYXJlZS1yZWQteWVsbG93LXNrdS1zcmlwbC0yODU0Lmh0bWw,","product":"14","selected_configurable_option":"","related_product":"","qty":"1"}, "additional_options":[{"code":"vendor_name","label":"Vendor","value":"cf97wksk"}]}, "weight":null, "is_virtual":"0", "sku":"DKSR0000001-1", "name":"KLM Fashion Mall Women's Fancy Cotton Silk Saree ( RED & YELLOW )", "description":null, "applied_rule_ids":null, "additional_data":null, "is_qty_decimal":"0", "no_discount":"0", "qty_backordered":null, "qty_canceled":"0.0000", "qty_invoiced":"0.0000", "qty_ordered":"1.0000", "qty_refunded":"0.0000", "qty_shipped":"0.0000", "base_cost":null, "price":"1846.6800", "base_price":"1846.6800", "original_price":"1846.6800", "base_original_price":"1846.6800", "tax_percent":"5.0000", "tax_amount":"294.5500", "base_tax_amount":"294.5500", "tax_invoiced":"0.0000", "base_tax_invoiced":"0.0000", "discount_percent":"0.0000", "discount_amount":"0.0000", "base_discount_amount":"0.0000", "discount_invoiced":"0.0000", "base_discount_invoiced":"0.0000", "amount_refunded":"0.0000", "base_amount_refunded":"0.0000", "row_total":"1846.6800", "base_row_total":"1846.6800", "row_invoiced":"0.0000", "base_row_invoiced":"0.0000", "row_weight":"0.0000", "base_tax_before_discount":null, "tax_before_discount":null, "ext_order_item_id":null, "locked_do_invoice":null, "locked_do_ship":null, "price_incl_tax":"2141.2300", "base_price_incl_tax":"2141.2300", "row_total_incl_tax":"2141.2300", "base_row_total_incl_tax":"2141.2300", "discount_tax_compensation_amount":"0.0000", "base_discount_tax_compensation_amount":"0.0000", "discount_tax_compensation_invoiced":null, "base_discount_tax_compensation_invoiced":null, "discount_tax_compensation_refunded":null, "base_discount_tax_compensation_refunded":null, "tax_canceled":null, "discount_tax_compensation_canceled":null, "tax_refunded":null, "base_tax_refunded":null, "discount_refunded":null, "base_discount_refunded":null, "free_shipping":"0", "gift_message_id":null, "gift_message_available":"0", "weee_tax_applied":null, "weee_tax_applied_amount":null, "weee_tax_applied_row_amount":null, "weee_tax_disposition":null, "weee_tax_row_disposition":null, "base_weee_tax_applied_amount":null, "base_weee_tax_applied_row_amnt":null, "base_weee_tax_disposition":null, "base_weee_tax_row_disposition":null, "vendor_id":"1", "seller_price":"1679", "hsn":"5007", "seller_item_total":"1678.80", "vendor_tax":"83.94", "vendor_row_total":"1762.74", "cess_rate":"0.00", "product":{}, "thumbnail":"\/1\/5\/1538546849_sku-sripl-2854_1.png", } } ] Array ( [shipping_address] => Array ( [entity_id] => 1 [parent_id] => 4 [customer_address_id] => 1 [quote_address_id] => 4 [region_id] => 564 [customer_id] => [fax] => [region] => Telangana [postcode] => 500049 [lastname] => Latname [street] => Road No 23 Deepthisree Nagar Madinaguda [city] => India [email] => asarush#xmial.com [telephone] => 9999999999 [country_id] => IN [firstname] => Aakshay [address_type] => shipping [prefix] => [middlename] => [suffix] => [company] => Aarush [vat_id] => [vat_is_valid] => [vat_request_id] => [vat_request_date] => [vat_request_success] => ) ) Array ( [billing_address] => Array ( [entity_id] => 2 [parent_id] => 4 [customer_address_id] => 1 [quote_address_id] => 10 [region_id] => 564 [customer_id] => [fax] => [region] => Telangana [postcode] => 500076 [lastname] => Gupta [street] => Road No 23 Golkonda [city] => Hyderabad [email] => fradnsss#gmail.com [telephone] => 9999999999 [country_id] => IN [firstname] => Firsthan [address_type] => billing [prefix] => [middlename] => [suffix] => [company] => Firstname [vat_id] => [vat_is_valid] => [vat_request_id] => [vat_request_date] => [vat_request_success] => ) ) Array ( [vendor] => Array ( [entity_id] => 1 [entity_type_id] => 9 [attribute_set_id] => 0 [increment_id] => 000000009 [parent_id] => 0 [created_at] => 2018-10-01 11:09:32 [updated_at] => 2018-11-27 12:55:57 [is_active] => 1 [website_id] => 1 [address] => hyyderabad [city] => hyderabad [zip_code] => 500055 [customer_id] => 1 [shop_url] => cf97wksk [status] => approved [group] => general [public_name] => cf97wksk [name] => Firstname Lastname [email] => testemail#gmail.com [contact_number] => 9999999999 [country_id] => IN [vendor_gstin] => 11PGTAU12346Q [gender] => 1 [region_id] => 564 ) ) In my controller sending the data to view as follows: $result = json_decode($result_json,true); return view('orders.view',compact('result')); I need to display shipping address and billing address in my view blade. How can i do that. I expect the out put like below Shipping Address Firstname Lastname Hyderabad Pin Code : 500072 Contact Number : 999888777
In your controller return view('view-name', [ 'shipping_address' => $shipping_address // ... ]); In your view-name.blade.php file: <input id="shipping_address" type="hidden" value="#json($shipping_address)"> In a Javascript file: let shipping_address= $('#shipping_address').val(); console.log(shipping_address) See console log in browser debug and you can do anything.
you cannot use $result->shipping_address because as per your output that is array. Try below one. echo $result[1]['shipping_address']['firstname'] . ' ' . $result[1]['shipping_address']['lastname'] . ' ' . $result[1]['shipping_address']['city'] . 'Pin code: ' . $result[1]['shipping_address']['postcode'] . ' ' . 'Contact Number : ' . $result[1]['shipping_address']['telephone']; or {{$result[1]['shipping_address']['firstname']}} {{$result[1]['shipping_address']['lastname']}} {{$result[1]['shipping_address']['city']}} Pin code: {{$result[1]['shipping_address']['postcode']}} Contact Number : {{$result[1]['shipping_address']['telephone']}} I have just provided option to print value, you may required some validation for variables. Thank you.
PHP: Store dynamically generated text field values in database
I have one array contains the result set from dynamically generated text box values. In the below example I created three dynamically generated rows and each row contains 6 text field. For differentiate each row name i added the row id as the last word of name. Example ClaimExecutionCountry1 means ClaimExecutionCountry as the name and 1 is the row id. Array ( [0] => ClaimExecutionCountry1=10 [1] => activitystartdate1=05-27-2016 [2] => activityenddate1=06-24-2016 [3] => CLCode1=CLC1 [4] => SCSCode1=SCS1 [5] => fileName1=calc2.png [6] => ClaimExecutionCountry2=53 [7] => activitystartdate2=05-27-2016 [8] => activityenddate2=05-28-2016 [9] => CLCode2= [10] => SCSCode2= [11] => fileName2=gh.png [12] => ClaimExecutionCountry3=82 [13] => activitystartdate3=05-26-2016 [14] => activityenddate3=07-28-2016 [15] => CLCode3= [16] => SCSCode3=SCS5 [17] => fileName3=preview1.png ) I am facing one issue for storing these values in Database. In my database structure is below Id | ClaimExecutionCountry | activitystartdate | activityenddate | CLCode | SCSCode | fileName I need to store after = symbol values in this table. after insert the table, the result would be Id | ClaimExecutionCountry | activitystartdate | activityenddate | CLCode | SCSCode | fileName ------------------------------------------------------------------------------------------------------------ 1 | 10 | 05-27-2016 | 06-24-2016 | CLC1 | SCS1 | calc2.png 2 | 53 | 05-27-2016 | 05-28-2016 | null | null | gh.png 3 | 82 | 05-26-2016 | 07-28-2016 | null | SCS5 | preview1.png So Anyone please help me to store the array values in database using above format. I think you understood my problem. I am using PHP,codignator and MySql as database. Thanks in advance
Please try code below: $_array=Array( [0] => ClaimExecutionCountry1=10 [1] => activitystartdate1=05-27-2016 [2] => activityenddate1=06-24-2016 [3] => CLCode1=CLC1 [4] => SCSCode1=SCS1 [5] => fileName1=calc2.png [6] => ClaimExecutionCountry2=53 [7] => activitystartdate2=05-27-2016 [8] => activityenddate2=05-28-2016 [9] => CLCode2= [10] => SCSCode2= [11] => fileName2=gh.png [12] => ClaimExecutionCountry3=82 [13] => activitystartdate3=05-26-2016 [14] => activityenddate3=07-28-2016 [15] => CLCode3= [16] => SCSCode3=SCS5 [17] => fileName3=preview1.png ) foreach($_array as $val){ $a = explode("=",$val); $field = $a[0]; $ans=$a[1]; $matches = array(); if (preg_match('#(\d+)$#', $field, $matches)) { $rowNum=$matches[1]; } $fieldName = str_replace($rowNum,"",$field); /*Now you have number of row , $fieldName , $rowNum and $ans so we can execute SQl statement inside forEach*/ } Hope it will help you.
$a = Array ( [0] => ClaimExecutionCountry1=10 [1] => activitystartdate1=05-27-2016 [2] => activityenddate1=06-24-2016 [3] => CLCode1=CLC1 [4] => SCSCode1=SCS1 [5] => fileName1=calc2.png [6] => ClaimExecutionCountry2=53 [7] => activitystartdate2=05-27-2016 [8] => activityenddate2=05-28-2016 [9] => CLCode2= [10] => SCSCode2= [11] => fileName2=gh.png [12] => ClaimExecutionCountry3=82 [13] => activitystartdate3=05-26-2016 [14] => activityenddate3=07-28-2016 [15] => CLCode3= [16] => SCSCode3=SCS5 [17] => fileName3=preview1.png ) Take the count of array------ $cnt = count($a); <!--now loop it and explode it to get the values after = --> for($i=0;$i<=$cnt;$i++){ $b = explode("=",$a[i]); <!--exploded value will give $b[0] = hhjhj and $b[1] = 10 ok --> $c[] = $b[1]; } <!-- In $c array all the values came after =.....now --> $k=0; $l=6; $h=0; for($j=$k;$j<=$l;$j++){ if($j == $l){ $j = $k; $l = $l + 5; $h++; } <!-- So from this here we got no of set of rows to be inserted in table --it will give result [3] from array $c(mixed values of no of rows) --> } <!-- now going to split into rows and insert--> for($i=1;$i<=3;$i++){ $e=6; for($j=0;$j<=$e;$j++){ if($j==$e){ $j=$e+1; $e = $e+6; break; }else{ $row[$i] = $c[$j]; } } } <!-- now we got --- --> $row[1] = {0,date,date,ccsc,sslc,image}; $row[2] = {0,date,date,ccsc,sslc,image}; $row[3] = {0,date,date,ccsc,sslc,image};
Increment a date with array of days
Actually my date is $Date= '03/02/2015'; I want to increment this day with array of days .My array is Array ( [0] => 1 [1] => 42 [2] => 70 [3] => 98 [4] => 186 [5] => 279 [6] => 372 [7] => 465 [8] => 558 [9] => 730 [10] => 1460 [11] => 4380 [12] => 1825 ). I stored this array in a variable called $data.I want to increment my date with each of this days and print all result dates.How can i do it???
Try this with this code you can print dates <?php $Date = "2015-02-03"; $dataArray = Array ( 1 ,42 , 70 , 98 , 186 , 279 ,372); foreach($dataArray as $val){ echo date('Y-m-d', strtotime($Date. " + $val days"))."</br>"; } ?>
Use this code <?php $Date= '03/02/2015'; $stamp= strtotime($Date); $days=array(42,70,98,186,279,372,465,558,730,1460,4380,1825); //change these values $values=array(); foreach($days as $day){ $newstamp=$stamp+($day*24*60*60); $values[]=date("m/d/Y",$newstamp); } //now add to database mysql_connect('localhost','user','pass'); //change user pass mysql_select_db('yourdatabase'); //change here foreach($values as $value) { $sql="insert into yourtable values('".$value."',xxx,xxxx..))"; //change here mysql_query($sql); } mysql_close(); ?>
PHP filter and sum array values
I've got a php script with following array (date,task,actor,hh:mm). Array ( [0] => 2013-01-29|Making movies|Laurel|07:30 [1] => 2013-01-29|Making movies|Hardy|00:30 [2] => 2013-01-29|Learning PHP|Hardy|07:00 [3] => 2013-01-29|Singing autographs|Keaton|07:30 [4] => 2013-01-29|Making movies|Lloyd|07:30 [5] => 2013-01-28|Learning PHP|Laurel|07:30 [6] => 2013-01-28|Making movies|Hardy|07:30 [7] => 2013-01-28|Learning PHP|Keaton|07:30 [8] => 2013-01-28|Making movies|Lloyd|07:30 [9] => 2013-01-27|Learning PHP|Laurel|05:30 [10] => 2013-01-27|Making movies|Laurel|02:30 [11] => 2013-01-27|Learning PHP|Hardy|07:30 [12] => 2013-01-27|Making movies|Keaton|07:30 [13] => 2013-01-27|Making movies|Lloyd|07:30 ) I'd like to create a filter that lists the tasks and sums the time values of each task, for example: Learning PHP (<-selected option) 2013-01-29 Hardy 07:00 2013-01-28 Laurel 07:30 2013-01-28 Keaton 07:30 2013-01-27 Laurel 05:30 2013-01-27 Hardy 07:30 ======================= TOTAL 35:00 What would be the way to make this happen? Any suggestions or next steps are more than welcome.
This would be easier to filter if you had a multidimensional array. Something like this would work for the current structure though: $task = "Learning PHP"; foreach($arr as $k=>$v) { $pieces = explode("|", $v); if($pieces[1]==$task) { $total += (int) str_replace(':','',$pieces[3]); echo $pieces[0] . " " . $pieces[2] . " " . $pieces[3]; } } echo "Total: " . $total;
PHP OOP: Weird Array Return
I have the following 'Course' class: class Course { // The constructor just sets the database object public function __construct($mysqli) { $this->mysqli = $mysqli; } public function getCourseInfoByID($id) { $result = $this->mysqli->query("SELECT * FROM courses WHERE id='$id'"); $course_info = $result->fetch_array(); // If found, return the student object if($course_info) { return $course_info; } return FALSE; } } When I declare the class and try to run the function "getCourseInfoByID", I get weird results (see below) $cid = process_get_request('cid'); $course = new Course($mysqli); if(! $course_info = $course->getCourseInfoByID($cid)) { $error[] = "Invalid Course ID"; setError(); redirectTo("instructors.php"); } print_r($course_info); I get this: Array ( [0] => 2 [id] => 2 [1] => 1 [course_type_id] => 1 [2] => 1 [instructor_id] => 1 [3] => Tooele [dz_name] => Tooele [4] => 4 Airport Road [dz_address] => 4 Airport Road [5] => Tooele [dz_city] => Tooele [6] => Utah [dz_state] => Utah [7] => 84020 [dz_zip] => 84020 [8] => [dz_email] => [9] => 2011-12-30 17:25:12 [created] => 2011-12-30 17:25:12 [10] => 2012-01-02 16:24:08 [start_date] => 2012-01-02 16:24:08 [11] => 2012-01-08 16:24:17 [end_date] => 2012-01-08 16:24:17 [12] => 10 [student_slots] => 10 [13] => Brett will also be assisting in teaching this course as Nathan's assistant. Brett paid Nathan quite well to be his assistant. [notes] => Brett will also be assisting in teaching this course as Nathan's assistant. Brett paid Nathan quite well to be his assistant. [14] => 0 [approved_by] => 0 [15] => 0000-00-00 00:00:00 [approved_on] => 0000-00-00 00:00:00 [16] => 0 [completed] => 0 ) Why is each record duplicated?
This is happening because you are returning both numeric and associative indexes. You should use fetch_assoc() or pass the appropriate constant MYSQLI_ASSOC or MYSQLI_NUM to return just those keys. See documentation on mysqli_result::fetch_array(). As an aside I would type hint your constructor to force the passing of a mysqli class so you can't accidentally pass an invalid argument.
Read the docs for the fetch_array() method. The second parameter defaults to MYSQLI_BOTH.