I have an array returned from Google Maps, that looks like this:
array(4) {
["destination_addresses"]=> array(4) {
[0]=> string(19) "Walsall WS2 9PS, UK"
[1]=> string(19) "Walsall WS2 9PS, UK"
[2]=> string(19) "Walsall WS2 9PS, UK"
[3]=> string(26) "Wolverhampton WV10 0QP, UK"
}
["origin_addresses"]=> array(1) {
[0]=> string(18) "Stone ST15 0FL, UK"
}
["rows"]=> array(1) {
[0]=> array(1) {
["elements"]=> array(4) {
[0]=> array(3) {
["distance"]=> array(2) {
["text"]=> string(7) "41.9 km"
["value"]=> int(41947)
}
["duration"]=> array(2) {
["text"]=> string(7) "36 mins"
["value"]=> int(2134)
}
["status"]=> string(2) "OK"
}
[1]=> array(3) {
["distance"]=> array(2) {
["text"]=> string(7) "41.9 km"
["value"]=> int(41947)
}
["duration"]=> array(2) {
["text"]=> string(7) "36 mins"
["value"]=> int(2134)
}
["status"]=> string(2) "OK"
}
[2]=> array(3) {
["distance"]=> array(2) {
["text"]=> string(7) "41.9 km"
["value"]=> int(41947)
}
["duration"]=> array(2) {
["text"]=> string(7) "36 mins"
["value"]=> int(2134)
}
["status"]=> string(2) "OK"
}
[3]=> array(3) {
["distance"]=> array(2) {
["text"]=> string(7) "40.9 km"
["value"]=> int(40924)
}
["duration"]=> array(2) {
["text"]=> string(7) "41 mins"
["value"]=> int(2458)
}
["status"]=> string(2) "OK"
}
}
}
}
["status"]=> string(2) "OK"
}
I want to be able to run through the array, and print the destination address and the distance and time values.
This prints the destination addresses ok:
$length=count($properties);
for($a=0;$a<$length;$a++)
{
echo '</br>Index is ' . $a . ' | id is ' . $index[$a] . ' | destination is ' . $properties["destination_addresses"][$a] . ' | time is ';
}
But I can't figure out how to print the rest. I've been banging my head against the wall all night!
Thank you in anticipation.
To loop over all these journeys and print the distance and time for each potential journey, create a foreach loop and then use the $idx to address the subordinate parts of the muleiple arrays
foreach( $destination['destination_addresses'] as $idx => $to ) {
if ( $destination['rows'][0]['elements'][$idx]['status'] == 'OK' ) {
echo 'Going from ' . $destination['origin_addresses'][0];
echo ' To ' . $to;
echo ' Distance ' . $destination['rows'][0]['elements'][$idx]['distance']['text'];
echo ' Duration ' . $destination['rows'][0]['elements'][$idx]['duration']['text'];
} else {
//whatever you do if the status is not OK
}
}
Related
Im trying many days now to select data from this db
[1]: https://i.stack.imgur.com/QA34L.jpg
I want to print for example all comments
echo $comment['username']." | "; \ Alex | Alex
My php code so far:
[![$m= new MongoDB\Client ("mongodb://127.0.0.1/");
$db = $m->stores;
$collection = $db->storeinfo;][1]][1]
$storez = $collection->find(array("Products.pTHUMBNAIL" => $pThumb));
$o=1;
$afm=array();
foreach ($storez as $stor) {
$afm[$o] = $stor['AFM'];
$record = $collection->findOne(array(
"AFM" => $afm[$o],"Products.pTHUMBNAIL" => $pThumb));
foreach ($record['Products'] as $pro){
if($pThumb == $pro['pTHUMBNAIL']){
echo $temp = $pro['pID']." ";
foreach($pro as $pro1['pCOMMENTS']) {
foreach($pro1 as $com['Comment']) {
var_dump($com['Comment']);
/*
foreach($com as $comment) {
echo $comment['username'];
}
*/
}
}
}
}
$o += 1;
}
It seems that i just cannot find the correct foreach to loop through my Comment array
var_dump output:
099360111/1 object(MongoDB\BSON\ObjectId)#55 (1) { ["oid"]=> string(24) "6003403a695900000c002649" } string(11) "099360111/1" string(9) "Old Skool" string(2) "75" string(4) "Vans" string(25) "Leather and textile upper" string(2) "44" string(18) "Men/Shoes/Trainers" string(52) "http://127.0.0.1/pricedoc/assets/img/products/p1.jpg" string(1) "7" object(MongoDB\Model\BSONArray)#65 (1) { ["storage":"ArrayObject":private]=> array(1) { [0]=> object(MongoDB\Model\BSONDocument)#10 (1) { ["storage":"ArrayObject":private]=> array(1) { ["Comment"]=> object(MongoDB\Model\BSONDocument)#73 (1) { ["storage":"ArrayObject":private]=> array(4) { ["username"]=> string(4) "Alex" ["date"]=> object(MongoDB\BSON\UTCDateTime)#45 (1) { ["milliseconds"]=> string(13) "1611028053000" } ["text"]=> string(21) "1st comment from user" ["rating"]=> string(1) "4" } } } } } } 099360666/1 object(MongoDB\BSON\ObjectId)#44 (1) { ["oid"]=> string(24) "6006563a3f1c0000c80034a8" } string(11) "099360666/1" string(12) "old school 2" string(2) "50" string(4) "Vans" string(11) "black/white" string(8) "42,43,43" string(18) "Men/Shoes/Trainers" string(52) "http://127.0.0.1/pricedoc/assets/img/products/p1.jpg" string(1) "6" object(MongoDB\Model\BSONArray)#79 (1) { ["storage":"ArrayObject":private]=> array(2) { [0]=> object(MongoDB\Model\BSONDocument)#7 (1) { ["storage":"ArrayObject":private]=> array(1) { ["Comment"]=> object(MongoDB\Model\BSONDocument)#39 (1) { ["storage":"ArrayObject":private]=> array(4) { ["username"]=> string(4) "Alex" ["date"]=> object(MongoDB\BSON\UTCDateTime)#68 (1) { ["milliseconds"]=> string(13) "1611028089000" } ["text"]=> string(21) "1st comment from user" ["rating"]=> string(1) "4" } } } } [1]=> object(MongoDB\Model\BSONDocument)#78 (1) { ["storage":"ArrayObject":private]=> array(1) { ["Comment"]=> object(MongoDB\Model\BSONDocument)#77 (1) { ["storage":"ArrayObject":private]=> array(4) { ["username"]=> string(4) "Alex" ["date"]=> object(MongoDB\BSON\UTCDateTime)#76 (1) { ["milliseconds"]=> string(13) "1611030745000" } ["text"]=> string(8) "good!!!!" ["rating"]=> string(1) "5" } } } } } }
What about this?
After echo $temp = $pro['pID']." ";
foreach($pro['pCOMMENTS'] as $comments) {
foreach ($comments['Comment'] as $comment) {
echo $comment['text'];
}
}
You used foreach() bad: the index should be added to the first parameter, not in the 'as' part.
Also it helps if you use more clear variable names. That doesn't take too much, but makes it more readable and easy to debug.
After echo $temp = $pro['pID']." ";
foreach($pro['pCOMMENTS'] as $comments) {
foreach($comments as $comment) {
echo $comment['text'];
}
}
array(2) { [0]=> array(2) { ["name"]=> string(16) "Daerah Pertanian" ["sub"]=> array(6) { [0]=> array(2) { ["name"]=> string(5) "Sawah" ["value"]=> string(3) "145" } [1]=> array(2) { ["name"]=> string(18) "Sawah Pasang Surut" ["value"]=> string(3) "455" } [2]=> array(2) { ["name"]=> string(6) "Ladang" ["value"]=> string(3) "678" } [3]=> array(2) { ["name"]=> string(10) "Perkebunan" ["value"]=> string(3) "688" } [4]=> array(2) { ["name"]=> string(19) "Perkebunan Campuran" ["value"]=> string(3) "966" } [5]=> array(2) { ["name"]=> string(16) "Tanaman Campuran" ["value"]=> string(3) "565" } } } [1]=> array(2) { ["name"]=> string(22) "Daerah Bukan Pertanian" ["sub"]=> array(2) { [0]=> array(2) { ["name"]=> string(18) "Hutan Lahan Kering" ["sub"]=> array(2) { [0]=> array(2) { ["name"]=> string(25) "Hutan Lahan Kering Primer" ["value"]=> string(3) "566" } [1]=> array(2) { ["name"]=> string(27) "Hutan Lahan Kering Sekunder" ["value"]=> string(3) "255" } } } [1]=> array(2) { ["name"]=> string(17) "Hutan Lahan Basah" ["sub"]=> array(2) { [0]=> array(1) { ["name"]=> string(24) "Hutan Lahan Basah Primer" } [1]=> array(1) { ["name"]=> string(26) "Hutan Lahan Basah Sekunder" } } } } } }
I have an array like I mention above, so I want to print out every "name" key including the index (number) of it's array parent,
for example when I print out "Tanaman Campuran" so all index parent is (0)(5) and when I print "Hutan Lahan Basah Sekunder" the index parent is (1)(1)(1)
how can I achieve it?
here is some recursive function that I've tried
$GLOBALS['all'] = '';
function printout($arr){
foreach ($arr as $ia=>$a){
if(is_array($a)){
foreach ($a as $ib=>$b){
if(is_array($b)){
printout($b);
}
else{
if ($ib == 'name') {
$GLOBALS['all'] .= $ia;
echo '<tr>';
echo '<td>' . $b . ' (' . $ia . ')</td>';
echo '</tr>';
$GLOBALS['all'] = '';
}
}
}
}
}
}
*sorry for my bad explanation, I hope you guys can understand it
You could use the following function:
function search(array $array, $name)
{
foreach ($array as $key => $entry) {
if ($entry['name'] === $name) {
return [$key];
}
if (isset($entry['sub']) && $found_keys = search($entry['sub'], $name)) {
return array_merge([$key], $found_keys);
}
}
return null;
}
It returns:
if the value was directly found, an array of one containing the associated index,
if it wasn't but was found in any descendant item, an array merging its index with the indices of said descendant,
null if it wasn't found in that part of the tree.
Note: if a given name is present several times, it will only find the first occurrence.
Demo: https://3v4l.org/1hGr1
I have written below lines of code
public function shiftarray($cursor, $arg)
{
$keyarguments = array("first_name","roll_no");
$arrayStudents =array();
foreach ($cursor as $k => $row)
{
foreach ($keyarguments as $key)
{
if (strcasecmp($row[$key], $arg) == 0)
{
array_unshift($arrayStudents, $row);
}
else
{
}
}
}
return $arrayStudents;
}
I have array of students in $cursor like
{ [0]=> array(50) { ["_id"]=> object(MongoId)#23 (1) { ["$id"]=> string(24) "58131c7799fbad4c1d000202" } ["student_id"]=> float(2) ["registration_temp_perm_no"]=> string(1) "1" ["roll_no"]=> float(1) ["admission_date"]=> string(10) "01/07/2016" ["first_name"]=> string(7) "Neil" ["middle_name"]=> string(4) "David" ["last_name"]=> string(6) "Stephan" ["dob"]=> string(10) "12/03/1981" ["gender"]=> string(6) "Female" ["blood_group"]=> string(2) "A+" ["birth_place"]=> string(11) "Sadar Bazar" ["nationality"]=> string(6) "Indian" ["language"]=> string(7) "English" ["religion"]=> string(8) "Agnostic" ["address_line1"]=> string(20) "4148 Hazelcrest Hill" ["address_line2"]=> string(20) "22883 Memorial Place" ["city"]=> string(11) "Sadar Bazar" ["state"]=> string(13) "Uttar Pradesh" ["pincode"]=> string(6) "190010" ["country"]=> string(5) "India" ["phone1"]=> string(10) "9039180419" ["phone2"]=> string(10) "7681559402" ["email"]=> string(24) "educianstudent#gmail.com" ["is_sms_enabled"]=> string(3) "Yes" ["is_active"]=> int(1) ["has_finished"]=> int(0) ["student_category"]=> string(1) "5" ["course"]=> string(24) "58131c7099fbad4c1d0001c2" ["Biometric_ID"]=> string(1) "1" ["siblings"]=> string(14) "Cynthia Taylor" ["guardian_name"]=> string(14) "Cynthia Taylor" ["guardian_occupation"]=> string(13) "Senior Editor" ["guardian_qualification"]=> string(20) "Research Assistant I" ["guardian_email_id"]=> string(23) "educianparent#gmail.com" ["gaurdain_contact_details"]=> string(10) "9419513603" ["guardian_relationship"]=> string(6) "Father" ["height"]=> string(3) "4.9" ["weight"]=> string(4) "34.9" ["allergies"]=> string(0) "" ["batch"]=> int(2) ["academicyear"]=> string(4) "2015" ["batchhistory"]=> array(1) { [0]=> array(5) { ["batchid"]=> float(2) ["academic_year"]=> string(4) "2015" ["course"]=> string(24) "58131c7099fbad4c1d0001c2" ["sequenceno"]=> int(1) ["courseId"]=> object(MongoId)#24 (1) { ["$id"]=> string(24) "58131c7099fbad4c1d0001c2" } } } ["uploads"]=> array(1) { ["profile_pic"]=> string(39) "58131c7799fbad4c1d000202schoolgirl2.jpg" } ["created_at"]=> NULL ["updated_at"]=> string(0) "" ["routearray"]=> array(2) { [0]=> array(5) { ["routeid"]=> int(2) ["academicyear"]=> string(4) "2016" ["current"]=> int(0) ["vehicleno"]=> string(9) "JK01S8764" ["dateofassignment"]=> string(10) "09/28/2016" } [1]=> array(5) { ["routeid"]=> int(3) ["academicyear"]=> string(4) "2016" ["current"]=> int(1) ["vehicleno"]=> string(9) "JK01S8764" ["dateofassignment"]=> string(10) "11/17/2016" } } ["HostelAlloted"]=> array(7) { ["Food Preferences"]=> string(4) "Both" ["Hostel"]=> object(MongoId)#25 (1) { ["$id"]=> string(24) "58138aee99fbade41e000031" } ["Floor"]=> string(7) "Floor_1" ["RoomNumber"]=> int(11) ["Approved"]=> string(3) "yes" ["Approved On"]=> object(MongoDate)#26 (2) { ["sec"]=> int(1472322600) ["usec"]=> int(0) } ["Academic Year"]=> string(4) "2016" } ["HostelAllotmentHistory"]=> array(1) { [0]=> array(7) { ["Food Preferences"]=> string(4) "Both" ["Hostel"]=> object(MongoId)#27 (1) { ["$id"]=> string(24) "58138aee99fbade41e000031" } ["Floor"]=> string(7) "Floor_1" ["RoomNumber"]=> int(11) ["Approved"]=> string(3) "yes" ["Approved On"]=> object(MongoDate)#28 (2) { ["sec"]=> int(1472322600) ["usec"]=> int(0) } ["Academic Year"]=> string(4) "2016" } } ["courseId"]=> object(MongoId)#29 (1) { ["$id"]=> string(24) "58131c7099fbad4c1d0001c2" } }
...
...
I am trying to bring those student on the beginning of array whose first name is brian and rest of students should at the bottom.
Now the above code place the students on the top of the array but the rest of the students are ommited/removed. I don't want them to be removed.
I am trying to tweak what code to write in else condition.
Please help!!!
Fill $arrayStudents before the loop otherwise only matches will be collected and unshifted.
Extend example of php.net/unshift
$add = array('big');
$queue = array(
array("orange"),
array("banana"),
array("apple1"),
array("raspberry")
);
array_unshift($queue, $add);
print_r($queue);
In your case: search for keys you want to unshift, the rest goes to the standard $list = array(/list of studends/):
$list = array();
$bringToTop = array('brian', 'elvis');
foreach($data as $item) {
if (/* in in the list to bring on top*/) {
$memory[] = $item;
} else {
$list[] = $item;
}
}
foreach($memory as $item) {
array_unshift($list, $item);
}
print_r($list);
Kind regards
Add $arrayStudents[] = $row; to your else scope. Here is a simple demo to illustrate it.
When matches add the element to the result from the start of array, unmatches add them from the end of the array.
i have two csv files: one contracts data and the other containing awarded contracts. I need to combine these two files using common field(contractname) and compute total amount of current awarded contracts.
Link to csv files:
https://github.com/younginnovations/problem-statements/tree/master/clean-up-contracts-data
I do get desired output bt undefined offset error comes up.
the code:unset(awards_info[$y][0]); does unsets the data but 'Undefined offset: 0' error occurs..
similarly the code $list_data[10]!=NULL also shows the same error
but both are producing desired output.
var_dump($awards_info):: produces following:
array(5) { [0]=> array(6) { [0]=> string(12) "contractName" [1]=> string(12) "contractDate" [2]=> string(14) "completionDate" [3]=> string(7) "awardee" [4]=> string(15) "awardeeLocation" [5]=> string(6) "Amount" } [1]=> array(6) { [0]=> string(15) "Contract-2070-3" [1]=> string(8) "5/9/2014" [2]=> string(9) "8/25/2014" [3]=> string(11) "SK Builders" [4]=> string(5) "Banke" [5]=> string(6) "200000" } [2]=> array(6) { [0]=> string(15) "Contract-2070-5" [1]=> string(9) "3/18/2014" [2]=> string(8) "4/8/2014" [3]=> string(24) "S engineering industries" [4]=> string(9) "Makwanpur" [5]=> string(6) "300000" } [3]=> array(6) { [0]=> string(15) "Contract-2070-9" [1]=> string(8) "3/6/2014" [2]=> string(8) "4/6/2014" [3]=> string(24) "Gourishankar nirman sewa" [4]=> string(8) "Lalitpur" [5]=> string(6) "400000" } [4]=> array(6) { [0]=> string(16) "Contract-2070-10" [1]=> string(8) "2/6/2014" [2]=> string(9) "6/16/2014" [3]=> string(11) "SK Builders" [4]=> string(5) "Banke" [5]=> string(6) "400000" } }
$file_contract=fopen('contracts.csv','r');
$file_awards=fopen('awards.csv','r');
while(($data=fgetcsv($file_contract))!=FALSE){
$contracts_info[]=$data;
}
while(($data=fgetcsv($file_awards))!=FALSE){
$awards_info[]=$data;
}
$con_count=count($contracts_info);
for($x=0;$x<$con_count;$x++){
if($x==0){
unset($awards_info[0][0]);
$data[$x]=array_merge($contracts_info[0],$awards_info[0]);
}
else{
$check=0;
$award_count=count($awards_info);
for($y=1;$y<$award_count;$y++){
if($awards_info[$y][0]==$contracts_info[$x][0]){
unset($awards_info[$y][0]);
$data[$x]=array_merge($contracts_info[$x],$awards_info[$y]);
$check=1;
}
}
if($check==0){
$data[$x]=$contracts_info[$x];
}
}
}
$final_data=fopen('final.csv','w');
foreach($data as $list_data){
fputcsv($final_data,$list_data);
}
fclose($final_data);
$c=0;
foreach ($data as $list_data){
if(($list_data[1]=='Current') && ($list_data[10]!=NULL))
{
$c+=$list_data[12];
}
}
echo $c;
You can just add the content file in the new file, without parsing files :
$fp = fopen('final.csv','w');
fwrite($fp, file_get_contents('contracts.csv'));
fwrite($fp, file_get_contents('awards.csv'));
fclose($fp);
echo file_get_contents('final.csv');
ok it's a wrong way. So i try to rewrite the loop :
for($x=0; $x < count($contracts_info); $x++) {
$data[$x] = $contracts_info[$x];
if($x == 0) {
if(isset($awards_info[$x])) {
$data[$x] = array_merge($data[$x], $awards_info[$x]);
unset($awards_info[$x]);
}
} else {
foreach($awards_info as $y => $award_info_datas) {
if($award_info_datas[0] == $contracts_info[$x][0]) {
$data[$x] = array_merge($data[$x], $award_info_datas);
unset($awards_info[$y]);
break;
}
}
}
}
I'm trying to use the library jmathai/twitter-async to send tweets, but I get an exception with no message :
//not logged in:
if($oauth_token == '')
{
try
{
$authorizationUrl = $twitterObj->getAuthorizeUrl();
/*
if (isset($authorizationUrl))
{
$twitterMessage = '<p>'._('twitter.signin.message').' : '.
'<a href="'. $authorizationUrl. '">'.
'<img class="signin" src="images/sign-in.png" /></a></p>';
}
else
{
$twitterMessage .= '<p>'._('twitter.error.message').' (error 1)</p>';
}
*/
}
catch(EpiTwitterException $e)
{
$twitterMessage .= 'epiError '.$e->getCode() . ' ' . $e->getMessage();
}
catch(EpiOAuthException $e)
{
$twitterMessage .= 'oAutherror: '$e->getCode() . ' ' . $e->getMessage();
}
}
This echoes "oAutherror: 0 "
Here's the result of var_dump($e->getTrace()); :
array(3) {
[0]=>
array(6) {
["file"]=>
string(70) "/.../lib/jmathai-twitter-async/EpiOAuth.php"
["line"]=>
int(404)
["function"]=>
string(5) "raise"
["class"]=>
string(17) "EpiOAuthException"
["type"]=>
string(2) "::"
["args"]=>
array(2) {
[0]=>
object(EpiCurlManager)#3 (2) {
["key:private"]=>
string(14) "Resource id #8"
["epiCurl:private"]=>
object(EpiCurl)#2 (9) {
["mc:private"]=>
resource(7) of type (curl)
["msgs:private"]=>
NULL
["running:private"]=>
NULL
["execStatus:private"]=>
NULL
["selectStatus:private"]=>
NULL
["sleepIncrement:private"]=>
float(1.1)
["requests:private"]=>
array(1) {
["Resource id #8"]=>
resource(8) of type (Unknown)
}
["responses:private"]=>
array(1) {
["Resource id #8"]=>
array(6) {
["data"]=>
bool(false)
["code"]=>
int(0)
["time"]=>
float(0)
["length"]=>
float(0)
["type"]=>
bool(false)
["url"]=>
string(43) "https://api.twitter.com/oauth/request_token"
}
}
["properties:private"]=>
array(5) {
["code"]=>
int(2097154)
["time"]=>
int(3145731)
["length"]=>
int(3145743)
["type"]=>
int(1048594)
["url"]=>
int(1048577)
}
}
}
[1]=>
bool(false)
}
}
[1]=>
array(6) {
["file"]=>
string(70) "/.../lib/jmathai-twitter-async/EpiOAuth.php"
["line"]=>
int(53)
["function"]=>
string(5) "__get"
["class"]=>
string(16) "EpiOAuthResponse"
["type"]=>
string(2) "->"
["args"]=>
array(1) {
[0]=>
string(11) "oauth_token"
}
}
[2]=>
array(6) {
["file"]=>
string(44) "/.../main.inc.php"
["line"]=>
int(29)
["function"]=>
string(15) "getAuthorizeUrl"
["class"]=>
string(8) "EpiOAuth"
["type"]=>
string(2) "->"
["args"]=>
array(0) {
}
}
The problem seems to have gona way when I removed the certificate from the folder (file named ca_bundle.crt).
See https://github.com/jmathai/twitter-async/issues/134