I am parsing .ini file which looks like this (structure is same just much longer)
It is always 3 lines for one vehicle. Each lines have left site and right site. While left site is always same right site is changing.
00code42=52
00name42=Q7 03/06-05/12 (4L) [V] [S] [3D] [IRE] [52]
00type42=Car
00code43=5F
00name43=Q7 od 06/12 (4L) [V] [S] [3D] [5F]
00type43=Car
What I am doing with it is:
$ini = parse_ini_file('files/models.ini', false, INI_SCANNER_RAW);
foreach($ini as $code => $name)
{
//some code here
}
Each value for each car is somehow important for me and I can get to each it but really specifily and I need your help to find correct logic.
What I need to get:
mCode (from first car it is 00)
code (from first car it is 52)
vehicle (from first car it is Q7 03/06-05/12 (4L))
values from [] (for first car it is V, S, 3D, IRE , 52
vehicle type ( for first car it is "car")
How I get code from right site:
$mcode = substr($code, 0, 2); //$code comes from foreach
echo "MCode:".$mcode;
How I get vehicle type:
echo $name; // $name from foreach
How I parse values like vehicle and values from brackets:
$arr = preg_split('/\h*[][]/', $name, -1, PREG_SPLIT_NO_EMPTY); // $name comes from foreach
array(6) { [0]=> string(19) "Q7 03/06-05/12 (4L)" [1]=> string(1) "V" [2]=> string(1) "S" [3]=> string(2) "3D" [4]=> string(3) "IRE" [5]=> string(2) "52" }
So basicly I can get to each value I need just not sure how to write logic for work with it.
In general I can skip the first line of each car because all values from there is in another lines as well
I need just 2th and 3th line but how can I skip lines like this? (was thinking to do something like :
if($number % 3 == 0) but I dont know how number of lines.
After I get all data I cant just echo it somewhere but I also need to store it in DB so how can I do this if
I will really appriciate your help to find me correct way how to get this data in right cycle and then call function to insert them all to DB.
EDIT:
I was thinking about something like:
http://pastebin.com/C97cx6s0
But this is just structure which not working
If your data is consistent, use array_chunk, array_keys, and array_values
foreach(array_chunk($ini, 3, true) as $data)
{
// $data is an array of just the 3 that are related
$mcode = substr(array_keys($data)[0], 0, 2);
$nameLine = array_values($data)[1];
$typeLine = array_values($data)[2];
//.. parse the name and type lines here.
//.. add to DB
}
Related
I’m new to PHP so this might be a very long questions. First of all I can’t normalise the database the way it has been designed it has to be kept like this. I’ll explain the scenario first: I have locations on a map, those locations can have as many products attached to them as possible. My issue is that I want to concatenate two values together in an array to make them into a string so I can store it in the db and then use it.
I’m having issues with a particular record, this record 1234 is causing me issues. As it has two Ratings attached to it but I need to concatenate them and put them into another array so I can store in my database in a particular field as strings instead of separate ints.
Below is the code, as you’ll see I did a if statement inside the code I want to use to debug what is happening in that particular record.
$ratingString = array();
$rating = 0;
foreach( //not sure if this foreach is related to the question)
if(true == isset($ratingString[$location[‘id’]])){
echo ‘in set’;
$ratingString[$location[‘id’]][‘ratingString’] = strval( $ratingString[$location[‘id’]][‘ratingString’]).’,’.$rating;
}else {
if($location[‘id’] == 1234){
echo ‘not in set’
$ratingString[$location[‘id’]][‘ratingString’] = $rating;
Print_r($ratingString);
} }
When I debug this, it shows me two variables in rating string.
Not in set
string() “ratingString”
array(1){
[1234] =>
array(1) {
[“ratingString”] =>
int(2)
}
}
Not in set
string() “ratingString”
array(1){
[1234] =>
array(1) {
[“ratingString”] =>
int(3)
}
}
So what I need help with, is how could I concatenate the two so that it would be [ratingString] => string 2,3 and how would I change my code so that it would work for all my locations and not just this particular record.
I am storing all of my items into lines in a text file like so, with the ID at the start
1/item name/content/etc
2/item name/content/etc
3/item name/content/etc
4/item name/content/etc
This method of storage is for a simple script we are using on a game that is editable by the different users so security really isn't a big deal, or else we would just use mysqli and the like.
I need to be able to print out variable information for a single entry, found by the id at the beginning, and also print say, 3 and 2, in numerical order. So far I am loading them into an array like so
$content = file('script/items.txt');
$items = array($content);
it throws the whole file into an array like this
array(1) {
[0]=> array(4) {
[0]=> string(23) "1/item name/content/etc"
[1]=> string(23) "2/item name/content/etc"
[2]=> string(23) "3/item name/content/etc"
[3]=> string(23) "4/item name/content/etc"
}
}
is there an easier way to pick one, or even multiple using just their id so i don't have to store the whole file into the array (it could get big in the future) or is the best way to store them all, loop through the entire array one line at a time, explode them for each /, and them compare is it's in the required items? Thanks.
You need to use file() flags FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES
Do like below:-
$content = file('script/items.txt',FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
print_r($content);
Note:-
Now loop over the array to get records one-by-one.
Best approach to save data to database table with columns like id,item_name,contents and extra
You can try the below code to read file line by line.
$handle = fopen("script/items.txt", "r");
if ($handle) {
while (!feof($handle)) {
$line = fgets($handle)
// do your stuffs.
}
fclose($handle);
} else {
// error opening the file.
}
It will not load complete file in memory so you can use this for bigger files as well.
feof($handle) It will save you in case you have a line which contains a boolean false.
You could also use array_reduce to store the ID as key into the array.
$content = file('script/items.txt',FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$content = array_reduce($content, function ($result, $line) {
list($id, $data) = explode('/', $line, 2) ;
$result[$id] = $data;
return $result;
}, array());
print_r($content);
Outputs:
Array
(
[1] => item name/content/etc
[2] => item name/content/etc
[3] => item name/content/etc
[4] => item name/content/etc
)
So you can get elements using without using a loop:
$content[$wanted_id]
I want to echo a different image depending on if a key exists or not.
Here is an example of the array I'm using
["Person"] => array(11) {
["id"] => int(38482818123)
["weight"] => int(140)
["height"] => int(65)
}
["Name"] => array(2) {
["firstname"] => string(4) "John"
["lastname"] => string(5) "Smith"
}
So the name field isn't always there. I need to showimage a if the name is there and image b if there is no name.
What I've tried:
foreach($personArray as $person)
{
if ($person['Name'] != '')
{
echo "<img src='image-a.png'>";
}
else
{
echo "<img src='image-b.png'>";
}
}
Now the problem I have is that even though the person has a name, I'm seeing both images on the page instead of just image a
I have also tried using array_key_exists("Name", $personArray); but for some reason I am getting bool(false) as a result.
First, it seems that you have a different array for the Name, I wonder why you don't have something like:
["Person"] => array(11) {
["id"] => int(38482818123)
["weight"] => int(140)
["height"] => int(65)
["firstname"] => string(4) "John"
["lastname"] => string(5) "Smith"
}
As per that case, the array index with the key "firstname" , "lastname" might not be set for some person. So you can check if that index is set using
isset();
function
Try:
foreach($personArray as $person)
{
if (isset($person['firstname']) && isset($person['lastname']) ) // You may use or as well ||
{
echo "<img src='image-a.png'>";
}
else
{
echo "<img src='image-b.png'>";
}
// Or as a short hand if statement:
echo (isset($person['firstname'])&& isset($person['lastname'])) ? "<img src='image-a.png'>" : "<img src='image-b.png'>";
}
Edit: 1
You still seem to be using two different arrays: Person and Name. Doing this, you cannot say which particular person has the name values or not:
For eg: if you have 10 persons and have the Name array with firstname, lastname for just 7 person then you will have person[0], person[1].....person[9] and Name[0]...Name[6].
As per your construct, there is no any reference / link between the Person and Name array. Suppose 1st person has Name, then Person[0] and Name[0] would represent the same person. But if the first 3 Person do not have Name, then Person[3] will have Name[0]...and so on, hence, it is not possible to identify to which Person does a particular Name array belong to. And Note: you cannot use Name["firstname"] inside the foreach() of Person. Because, your name array would be of the form Name[0]["firstname"], Name[0]["lastname"] and so on.
Bottom Line:
If possible, try to use / include the firstname, lastname in the Person array itself. That way, when iterating / looping through the Person array using foreach() you can check if each of these person have firstname , lastname or not: Hope this is clear.
You need to use empty() like below:-
if(!empty($personArray['person']['Name'])){
//image a code
}else{
//image b code
}
I'm trying to add 4 arrays into one array ($all_prices) and then check the values of each key in each individual array against $all_prices to make sure that they are unique. If they are not I want to add a 0 to the end of if to make it unique (so 0.50 becomes 0.500).
For some reason I'm getting the following error, despite the fact that I already changed the data type from decimal to varchar:
array_count_values(): Can only count STRING and INTEGER values!
Edit
Here is a snippet from dd($all_prices)
array(4) { [0]=> array(9) { ["14.45"]=> string(8) "sample 1" ["12.40"]=>
string(8) "sample 2" ["14.13"]=> string(8) "sample 3" ["15.11"]=>
string(8) "sample 4"
Code:
$all_prices = [$list_a_prices, $list_b_prices, $list_c_prices, $list_d_prices];
$price_count = array_count_values($all_prices);
foreach($list_b_prices as $key => $value){
if($price_count[$key] >= 2){
$key . "0";
}
}
Where am I going wrong? Is there is a way to leave the data type as Decimal?
I think you should not index by the prices, after all from a math point of view 5.0 and 5.00 does not make difference at all.
If you are obtaining values from a database you will get strigs everywhere. So you will have to cast (int)$key for the keys.
And in your foreach you are changing a temporary variable. $key exists only for the current iteration of the loop you will want to declare it as:
foreach($list_b_prices as &(int)$key => $value){
if($price_count[$key] >= 2){
$key . "0";
}
}
Note the ampersand and the casting to integer. Although i'm not sure which will come first. But again: I think indexing by some different value shall give you a better result.
What about a nested loop ?
$all_prices = [$list_a_prices, $list_c_prices, $list_d_prices];
foreach($list_b_prices as $key => $value){
foreach($all_prices as $array){
if(isset($array[$key])){
$list_b_prices[$key] .= '0';
}
}
}
Not elegant but it does the trick.
I am working on a CakePHP 2.x but right now my question has nothing to do with the syntax. I need a solution for this problem:
I have a table named messages in which there is a field name mobile numbers. The numbers are in this format:
12345678 and +9112345678 .. so they are both the same. The only difference is that in one number the country code is missing.
So I do this query in the database:
select the distinct numbers from messages tables..
Now it is taking these both numbers as distinct. But what I want is to take these both numbers as one.
How can I do this? In my DB there are several numbers with different country codes. Some have a country code and some don't, but I want to take both as one. The one in country code and the other without code. How can this be done?
At times now I have an array in which all the distinct numbers are stored. In this array there are numbers like this:
12345678 +9112345678
So now I don't know how to make a logic that I can take these numbers as one. If there is any solution for this then please share with some example code.
I don't think you can do this on the database level.
You would have to do something like this:
Create an array of all country codes (including + sign)
Fetch all the numbers from the database
Use array_map() and in the callback run strpos() against each
element in the country code array and if a match is made remove the
country code from the number
Finally after step 4 is finished run the number array through
array_unique()
CODE:
$country_codes = array('+91', '+61');
$numbers_from_db = array('33445322453', '+913232', '3232', '+614343', '024343');
$sanitized_numbers = array_map(function($number) use ($country_codes){
if(substr($number, 0, 1) === "0") {
$number = substr($number, 1);
return $number;
}
foreach($country_codes as $country_code) {
if(strpos($number, $country_code) !== false) {
$number = str_replace($country_code, "", $number);
return $number;
}
}
return $number;
}, $numbers_from_db);
$distinct_sanitized_numbers = array_unique($sanitized_numbers);
Tested and the out put of var_dump($distinct_sanitized_numbers) is:
array(4) {
[0]=>
string(11) "33445322453"
[1]=>
string(4) "3232"
[3]=>
string(4) "4343"
[4]=>
string(5) "24343"
}