PHP - How Should I Separate Date Strings From Sub Arrays Within The Main Array ?
Hi - I am passing $_POST data from an HTML form. The POST array looks like this:
Code: [Select] Array ( [location] => Array ( [0] => Collingwood [1] => Varsity ) [4] => 01 Apr 2012 [1] => 12 Apr 2012 [2] => 01 May 2012 [3] => 01 Jun 2014 [8] => 01 Jul 2012 [6] => 12 Aug 2012 [7] => 20 Apr 2013 [5] => 20 Apr 2014 [submit] => Save Changes ) I am using a foreach loop to separate the keys from the values. The $values include dates and locations. I then pass $values to strtotime to convert the dates to a Unix Time stamp. when strtotime sees the Locations - it throws a PHP error "strtotime() expects parameter 1 to be string, array given" so my question is what can I do to separate the Dates from the locations in order to avoid the error ? MANY THANKS to anyone who can give advice on this ! Similar TutorialsHi.. been a while since I have touched php and need some help. What I am trying to do is have my links pull text from separate php files, and load them into main table. Here is my old php code..used to work.. I had my index.php with my website template on it. In the table I want my info to appear i put this code. <?php /* START MAIN AREA HERE */ if($news) include("news.php"); elseif($bio) include("bio.php"); elseif($draw) include("draw.php"); elseif($pic) include("pic.php"); else include("news.php"); /* END HERE */?> My link looks like this. <A HREF="?news=x" ONMOUSEOVER="changeImages('home', 'images/home-over.gif'); return true;" ONMOUSEOUT="changeImages('home', 'images/home.gif'); return true;"> <IMG NAME="home" SRC="images/home.gif" WIDTH=69 HEIGHT=31 BORDER=0 ALT=""></A> Any help much appreciated! Hello, I'm working on a script for my chat software that will convert an array into a string and then can easily later on be put back into an array, I've already done this but when I did it I didn't think of sub-arrays. For example of an array: Code: [Select] $user_info = array( 'username' => 'test', 'other_info' => array( 'var' => 'value', 'var2' => 'value2' ) ); and that would change into something like this: user_info:{username:test, other_info:{var:value,var2:value2}} I do not care what the string looks like, above was just an example, any separators can be used. I just can't have it messed up by user input (a username with a character of a separator or something). The code I have works for this: Code: [Select] $user_info = array('id' => 1, 'username' => 2); and it outputs this as the string id=1&username=2& The code I use is: Code: [Select] function strtoarray($str) { $info = explode("&", $str); if (is_array($info)) foreach ($info as $data) { $data = explode("=", $data); if (is_array($data)) { if (!empty($data[0])) { if ($array[$data[0]]) { if (!is_array($array[$data[0]])) { $array[$data[0]] = array($array[$data[0]]); } $array[$data[0]][] = stripslashes(urldecode($data[1])); } else { $array[$data[0]] = stripslashes(urldecode($data[1])); } } } } return $array; } function arraytostr($array) { foreach ($array as $key => $value) { $str .= $key . "=" . addslashes(urlencode($value)) . "&"; } return $str; } I'm really not sure if regex is the way to go with this or what and that's really why I'm asking for help. I know I could do this with more explodes and what not but I feel as if there's probably a better way to do this and I'm just over complicating it. Thank you in advance. I can successfully concatenate strings and vars to assemble a php var using an echo statement like this: Code: [Select] echo "<input type='radio' id='radio_btn_" . $Row['question_number'] . "_0' name='question[question_" . $Row['question_number'] . "]' value='0' checked='checked' />"; However, when attempting to reference the same var in an IF statement, I can't seem to get the syntax right. I know this syntax is wrong, but I list it for reference to describe the issue I am trying to solve. Code: [Select] if ($_POST['radio_btn_' . $Row['question_number'] . '_0'] == '0'){ I also tried curly braces but can't arrive at a solution. Any advise would be appreciated.
Hi, simply put;
$abs="Bob Rob Sue";
how can I put into code, when "Bob1:2" is used, it finds a match of "Bob", and assigns the complete string of "Bob1:2" ? <?php $abs="Bob Rob Sue"; $abby="sometext Bob1:2 is Sue3:4 where Rob2:1 etc"; $nums = preg_replace('/[a-zA-Z]/', ' ', $abby); $lets = preg_replace('/[0-9]:?[^0-9]/', ' ', $abby); //$lets1=array_intersect($abs, $lets); $absArr = explode(' ', $abs); $abbyArr = explode(' ', $lets); $letsx=array_intersect($absArr, $abbyArr); //echo $letsx[0] . "</br>"; //############################################# $nums1='/(\d+\:\d+)/s'; preg_match_all($nums1, $nums, $nums2); foreach($nums2 as $numsx){ } $abi0="$letsx[0]+$numsx[0]"; $abi1="$letsx[1]+$numsx[1]"; $abi2="$letsx[2]+$numsx[2]"; $answer=$abi0."</br>".$abi1."</br>".$abi2."</br>"; echo $answer; ?>
current results: Hi all What is the best way to work with times that are stored without there date but with only one date field regarding both times? Thanks Hey guys, I need your help on this please. I am working on a php web application. I have a form that gets information for Supplier and his traveling details. The values are stored in arrays. I would like to store supplier details in Supplier table and the travelling details in the Travel table. Here is the code with the comments. <?php if (isset($_VARS['submitSuppliers'])) { //error checking starts here $isError = false; if (empty($_VARS['supplierName'])) { $isError = true; $_VARS['supplierRequest']['supplierName']['errorMessage'] = 'You need to provide a Supplier Name.'; } if (empty($_VARS['address'])) { $isError = true; $_VARS['supplierRequest']['address']['errorMessage'] = 'You need to provide an Address.'; } if (empty($_VARS['travel'])) { $isError = true; $_VARS['supplierRequest']['city']['errorMessage'] = 'You need to provide travelling details.'; } #this checks if there is no error and then proceeds to save form values if (!$isError) { #This function adds the details and Returns the autoincremented Supplier ID $SupId = add_suppliers($_VARS); if ($SupId) { #=== Now here I would like to save the travelling details in the Travel table using the generated supplier id # $travId = add_Travel($_VARS); //==== how do I segregate only travel details from the $_VARS array to store in travel table? REDIRECT('/supplier/index.html', array('confirmationMessage' => 'Your details have been saved.')); }else { notify_admin('supplierjoin.php'); } }else { $_VARS['supplierRequest']['errorMessage'] = "There was a problem with the information you provided. Please check the form and try again."; } } ?> Kindly help. Any comment or feedback is always welcome. Thank you Hello guys, need some help. Let us say i have an array = 2011 ipad 2011 ipad review 2011 ipad price 2011 ipad design 2011 ipad reviews review 2011 ipad 2011 ipad feature I would like to review all the array elements that contain "review"...So the final array should look like 2011 ipad 2011 ipad price 2011 ipad design 2011 ipad feature Thanks Hi all,
I am using foreach statement to gather records and program levenshtein to detect any misspellings and suggesting the correct words.
The thing is i am unable to convert all those strings into a single array.
After trying to correct this issue so many times, i wonder if it is really possible to convert strings into a single array?
Any input is welcome
Hi I am trying to search an array that comes from a power shell script, the array of strings that returns is ever changing as it receives variables from the script. Therefore I need to use preg_grep to search for the word "not" I am also using another array which inverts this I then need to compare these new two arrays to the original and separate the results $working and not working into a table. I would be most grateful for any advice/solutions. The preg_grep aren't displaying anything.
<?php
//phpinfo();
ini_set('display_errors', 'On');
error_reporting(0);//E_ALL
echo '<html>
<style>
body
{
font-family:Calibri,Helvetica,sans-serif;
font-size:100%;
}
</style>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript">
function uploadJS(){
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); };
var textAreaValue=document.getElementById(\'ServerList\').value;
var trimmedTextAreaValue=textAreaValue.trim();
if(trimmedTextAreaValue!="") {
document.myForm.submit();
} else{
alert("Server List Text Area is Empty");
}
};
var input=document.getElementById(\'fileSelect\').value;
if(input!="") {
document.myForm.submit();
} else{
alert("You have not selected a file, please select one to proceed.");
}
var handleFileSelect = function(e) {
var files = e.target.files;
if(files.length === 1) {
document.forms.myForm.filecsv.value = files[0].name;
}
}
};
</script>
</head>';
#Upload Code
$target = "D:\Web\Upload/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). "
has been uploaded";
}
else {
}
if ($uploaded_size > 150000)
{ echo "Your file is too large.<br>";
$ok=0;
}
if ($uploaded_type =="text/php")
{
echo "No PHP files<br>";
$ok=0;
}
if (!($uploaded_type=="text/csv")) { echo "<br>";
$ok=0;
}
$target = "upload/"; $target = $target . basename( $_FILES['uploaded']['name']) ; $ok=1; //This is our size condition
if ($uploaded_size > 350000)
{
echo "Your file is too large.<br>";
$ok=0;
}
//This is our limit file type condition
if ($uploaded_type =="text/php")
{ echo "No PHP files<br>";
$ok=0;
}
//Here we check that $ok was not set to 0 by an error
if ($ok==0)
{
}
//If everything is ok we try to upload it
else {
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
} else
{
}
}
#Start of scripts to check Servers in textbox
if(isset($_POST['ServerList']))
{
//$arry=explode( "\r\n", $_POST['ServerList'] );
$txttrim = trim($_POST['ServerList']);
//$textAr = explode("\n", $text);
//$textAr1 = array_filter($text, 'trim'); // remove any extra \r characters left behind
$txtarea = explode("\n",$txttrim);
$txtarea = array_filter($txtarea,'trim');
foreach ($txtarea as $line => $servername)
{
//$line => $servername;
##check if querying itself....
}
echo '<pre>';
$target="D:/Web/Upload/"; $target= $target . basename( $_FILES['uploaded']['name']) ;
$csv = $target;
//$filename= $_FILES['uploaded']['name'];
$output=shell_exec("powershell -Command D:/Web/scripts/PHPfwrules.ps1 $csv < NUL");
echo '<h6>';
print_r($output);
$nomatch=preg_grep('/^not/i',$output);
echo $nomatch;
$match=preg_grep("/not/",$output,PREG_GREP_INVERT);
echo $match;
if ($working1= array_intersect($output,$match))
{
echo"<link rel=stylesheet type=text/css href=style.css>
<table class=results>
<tr>
<th>Server Name</th>
<th>Working</th>
</tr>
<tr>
<td>".$servername."</td>
<td>".$working1."</td>
</tr></table>
";
}
else if ($notworking1= array_intersect($output,$nomatch))
{
echo"<link rel=stylesheet type=text/css href=style.css>
<table class=results>
<tr>
<th>Server Name</th>
<th>Not Working</th>
</tr>
<tr>
<td>".$servername."</td>
<td>".$notworking1."</td>
</tr></table>
";
}
}
echo' <link rel=stylesheet href=dhtmlwindow.css type=text/css />
<link rel=stylesheet type=text/css href=style.css>
<script src=js/dhtmlwindow.js></script>
<hr />
<table class=results>
<tr>
<th>Server Name</th>
<th>Working</th>
<th> Not Working</th>
</tr>
<tr>
<td>'.$servername.'</td>
<td>'.$working1.'</td>
<td>'.$notworking1.'</td>
<td></td>
';
echo '</pre>';
echo '
<h3>Firewall Implementation </h3>
<h4>Please enter the server below, you can only select one server at a time. </h4>
<!--The form-->
<form action="fw2.php" method="post" name="myForm" id="myForm" enctype="multipart/form-data">
<textarea name=ServerList id=ServerList>
</textarea>
<h5>Please select a CSV file.</h5>
<input name="uploaded" type="file" /><br />
<input type="submit" value="Submit" />
<br>
</html> '
;
?>
I am trying to locate an array in an array of arrays:
$card_pos = array_search($target, $_SESSION['leitner']['boxes'][($box - 1)]); if ($card_pos !== false) { // Do my stuff here }echo '<pre> oh no -- didn\'t find '; print_r($target); echo "in ";print_r ($_SESSION['leitner']['boxes'][($box + 1)]);echo '<br>leitner';print_r ($_SESSION['leitner']); echo '</pre>';but I don't find the target in the array though it is clearly there as you can see in the output: oh no -- didn't find Array ( [pos] => v5g [tense] => agerimasu ) in Array ( [0] => Array ( [pos] => v5g [tense] => agerimasu ) ) leitnerArray ( [boxes] => Array ( [1] => Array ( ) [2] => Array ( ) [3] => Array ( [0] => Array ( [pos] => v5g [tense] => agaru ) [1] => Array ( [pos] => v5g [tense] => agarimasu ) [2] => Array ( [pos] => v5g [tense] => agarimasen ) [3] => Array ( [pos] => v5g [tense] => agaranai ) [4] => Array ( [pos] => v5g [tense] => ageru ) [5] => Array ( [pos] => v5g [tense] => ageranai ) [6] => Array ( [pos] => v5g [tense] => agerimasen ) [7] => Array ( [pos] => v5g [tense] => agerimasend ) [8] => Array ( [pos] => v5g [tense] => agereba ) [9] => Array ( [pos] => v5g [tense] => agareba ) [10] => Array ( [pos] => v5g [tense] => agatte ) [11] => Array ( [pos] => v5g [tense] => agette ) ) [4] => Array ( [0] => Array ( [pos] => v5g [tense] => agerimasu ) ) [5] => Array ( ) ) [denom_total] => Array ( [1] => 0 [2] => 0 [3] => 36 [4] => 40 [5] => 40 ) [denom_max] => 40 ) Hey guys,
I have an array of names sorted alphabetically. I'm trying to loop through them and create new arrays keyed by the letters of the alphabet containing the names which start with that letter.
so in the end i'm trying to create something like this:
$newarray = array( 'a' => array('anna','alan','andrew'),
'b' => array('bert','ben','bob'), 'c' => array('cait','carry'), etc,etc ); thanks Hello, I have three arrays of integers $arrayA, $arrayB, and $arrayC. $ArrayA is a "master array" meaning the array I need to match the other two to. $arrayB and $arrayC are generated by my functions in the application and meet specific criteria. As such, arrays B and C will never have any intersecting values, but both should have matches in $arrayA, and I need to generate an array which contains only the values of arrayA which match either B or C. After finding some documentation here (http://www.metrocomp.mocsi.eu/w3/php/func_array_intersect.html) I tried using array_intersect : array_intersect ($arrayA, $arrayB, $arrayC) However this does not work as described and returns no results as there are no values which are contained in all three arrays. I wrote the below as a work around, and it works just fine but I would think there is a better way? $temp1 = array_intersect($arrA, $arrB); $temp2 = array_intersect($arrA, $arrC); $temp3 = array_merge($temp1, $temp2); $final_array = array_unique($temp3); Thanks for looking! Carmen Hey Guys. I came across this code example below assigns array values to a private property. However the private property is not defined as an array. It was a bit confusing to me because I always thought you need to define the property as an array first. If someone can please help me understand this concept I would really appreciate it.
Below is the code.
<?php class Product { public $name; public $price; function __construct($name, $price){ $this->name = $name; $this->price = $price; } } class ProcessSale { private $callbacks; // This holds an array but is not defined as an array? function registerCallback($callback) { if(!is_callable($callback)) { throw new Exception("Callback Is Not Callable"); } $this->callbacks[] = $callback; } function sale($product) { print "{$product->name}: processing \n"; foreach ($this->callbacks as $callback) { call_user_func($callback, $product); } } } $logger = function($product) { print "logging ({$product->name})\n"; }; $processor = new ProcessSale(); $processor->registerCallback($logger); $processor->sale(new Product("shoes", 6)); echo "\n"; $processor->sale(new Product("coffee", 6)); Here are the two arrays to compare. Peopleskills PeopleID SkillID 2 2 2 7 2 9 2 11 3 2 3 12 3 14 4 5 Equipskills EquipID SkillID 1 2 1 9 1 11 2 5 2 7 2 9 2 12 2 13 2 14 3 2 4 11 The common link is SkillID. Each EquipID has some required SkillIDs that people must have to operate that machine. As long as a PeopleID has the required SkillIDs from the EquipSkills, that person has permission to that machine. This will be used create a third array. It will look something like the following. EquipIDs 1 2 3 4 5 6 7 8 9 10 11 12 PeopleIDs 2 x x 3 x 4 5 What might be the best way to code this? I have a MySQL query that pulls multiple columns with many rows. I want to break each column into its own array. Here is what I have to this point but doesn't seem to be working. Is this the right direction or is there something easier? Thanks! Code: [Select] $query = "SELECT name, address, city, state FROM customers WHERE sku = '12345'"; $result = mysqli_query($dbc, $query) or die(); $name = array(); $address = array(); $city = array(); state = array(); while ($data = mysqli_fetch_assoc($result)) { $name = $data['name']; $address = $data['address']; $city = $data['city']; $state = $data['state']; } I have an array like this
$rows = array( array( 'fruit.name' => 'Apple', 'fruit.colour' => 'Red', 'fruit.weight' => '0.1', 'vegetable.name' => 'Carrot', 'vegetable.colour' => 'Orange', 'vegetable.weight' => '0.05' ), array( 'fruit.name' => 'Banana', 'fruit.colour' => 'Yellow', 'fruit.weight' => '0.7', 'vegetable.name' => 'Potato', 'vegetable.colour' => 'Brown', 'vegetable.weight' => '0.6' ) ); Hello!
First of all, I'm new here. I've been working with PHP for a few months and am really enjoying its capabilities
A little background on the project I'm doing at the mo, I'm creating a small dashboard for grabbing Twitter stats via the API. The result will eventually output in a pretty table showing the daily followers, follower gains (or losses) etc. Here's an example of the table I eventually want to end up with.
So far I have two arrays of data:
$accounts_data is a list of all account names and their associated ID's
$followers_data is a list of all follower counts, for a specific time of day, with an associated account ID (which matches the ID found in $accounts_data, thus pairing the follower count to a specific account)
I'm now trying to combine these two arrays into something more sensible that can then be used to output the table as shown in the link above.
$accounts_data:
array(4) { [0]=> array(2) { ["id"]=> string(4) "1279" ["name"]=> string(13) "AccountName1" } [1]=> array(2) { ["id"]=> string(4) "1280" ["name"]=> string(10) "AccountName2" } [2]=> array(2) { ["id"]=> string(4) "1281" ["name"]=> string(12) "AccountName3" } [3]=> array(2) { ["id"]=> string(4) "1283" ["name"]=> string(11) "AccountName4" } }$followers_data (truncated this data) array(12) { [0]=> array(3) { ["account_id"]=> string(4) "1279" ["date_time"]=> string(19) "2014-11-14 09:00:03" ["followers"]=> string(4) "1567" } [1]=> array(3) { ["account_id"]=> string(4) "1280" ["date_time"]=> string(19) "2014-11-14 09:00:29" ["followers"]=> string(4) "7688" } [4]=> array(3) { ["account_id"]=> string(4) "1279" ["date_time"]=> string(19) "2014-11-14 16:30:35" ["followers"]=> string(4) "1566" } } I have a really confusing question. I dynamically generate arrays, but for the simplicity of the example we can just use two arrays. Code: [Select] Array 1 ( [0] = 1 [1] = 5 ) Array 2 ( [0] = 2 [1] = 6 ) How can I make the arrays multiple based on the same key value? array 1[0] * array 2[0] = 2 array 1[1] * array 2[1] = 30 I then want to sum the total of the multiplication. $total = 2 + 30; I need to do this to calculate covariance for a statistics procedure I am trying to run but I can't wrap my head around how to do the logic. My array is $arr = array( 'global' => array( array('tabs', 'tabs', 'tabs', array( 'Main' => 'main', 'Gallery' => 'galleryID', 'mera' => 'mera', )), array('main','div', 'div'), array('egice', 'Eice', 'text', '', ''), array('closeHere', 'closeHere', 'closeHere'), array('galleryID','div', 'div'), array('gallery', 'Gallery #1', 'image', '', ''), array('closeHere', 'closeHere', 'closeHere'), array('networking', 'div', 'div'), array('siLype', 'SiLype', 'text', '', ''), array('gpXCge', 'GpXCge', 'toggle_button', '1', 'Yes', 'No', ''), array('closeHere', 'closeHere', 'closeHere'), array('mera', 'div', 'div'), array('maimera', 'Maimera', 'repeatedText', 'resYI', 'GYL',''), array('closeHere', 'closeHere', 'closeHere'), array( 'moures','div', 'div'), array('meLmo', 'MeLmo', 'text', '', ''), array('cYSlot', 'CYSlot', 'text', '', ''), array('closeHere', 'closeHere', 'closeHere'), array('clT', 'clT', 'clT'), ), );
Simply, I want to split the main array to multiple arrays
I had tried here to do it but I can’t |