I'm a beginner in PHP. I have a text file like this:
Name-Id-Number
Abid-01-80
Sakib-02-76
I can take the data as an array but unable to take it as an associative array. I want to do the following things:
Take the data as an associative array in PHP.
Search Number using ID.
Find out the total of Numbers
I believe I understand what you want, and it's fairly simple. First you need to read the file into a php array. That can be done with something like this:
$filedata = file($filename, FILE_IGNORE_NEW_LINES);
Now build your desired array using a foreach() loop, explode and standard array assignment. Your search requirement is unclear, but in this example, I make the associated array element into an array that is also an associative array with keys for 'id' and 'num'.
As you create the new array, you can compute your sum, as demonstrated.
<?php
$filedata = array('Abid-01-80', 'Sakib-02-76');
$lineArray = array();
$numTotal = 0;
foreach ($filedata as $line) {
$values = explode('-', $line);
$numTotal += $values[2];
$lineArray[$values[0]] = array('id' => $values[1], 'num' => $values[2]);
}
echo "Total: $numTotal\n\n";
var_dump($lineArray);
You can see this code demonstrated here
Updated response:
Keep in mind that notices are not errors. They are notifiying you that your code could be cleaner, but are typically suppressed in production.
The undefined variable notices are coming because you are using:
$var += $var without having initialized $var previously. Note that you were inconsistent in this practice. For example you initialized $numTotal, so you didn't get a notice when you used the same approach to increment it.
Simply add just below $numTotal = 0:
$count = 0;
$countEighty = 0;
Your other notices are occurring most likely due to a blank line or string in your input that does not follow the pattern expected. When explode is executed it is not returning an array with 3 elements, so when you try and reference $values = explode('-', $line); you need to make sure that $line is not an empty string before you process it. You could also add a sanity check like:
enter code hereif (count($values) === 3) { // It's ok to process
Related
I have general data array and I need to get array of specific data inside this general array so I can match it against my database.
Code
$nums = [];
foreach($request->phones as $phone) {
foreach($phone['_objectInstance']['phoneNumbers'] as $number) {
$nums = $number['value'];
}
}
$contacts = User::whereIn('phone', $nums)->get();
PS: $number['value'] is the data that I want to make array of it.
Sample data that I receive in backend
current error
Argument 1 passed to Illuminate\\Database\\Query\\Builder::cleanBindings() must be of the type array, string given, called in /home/....../vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php on line 918
exception: "TypeError"
Question
How can I make array of my numbers?
Ps: please if you know cleaner way to write this code, than my code above don't hesitate to share with me.
You're assigning $nums to be a new string on every iteration of the loop, rather than appending it to the array.
Just switch this line out:
$nums = $number['value'];
For
$nums[] = $number['value'];
Here are the docs for array_push(), which is the long way of writing the second line.
You are declaring $nums array, but inside the loop, you re-declaring it by a string again.
Fix the array assignments like that.
$nums[] = $number['value'];
Any idea on how to restructure the json below:
$jsonArray = [{"Level":"77.2023%","Product":"Milk","Temperature":"4"},
{"Level":"399.2023%","Product":"Coffee","Temperature":"34"},
{"Level":"109.2023%","Product":"Chocolate","Temperature":"14"}]
Expected outcome:
$expected = {"Milk":{"Level":"77.2023%","Temperature":"4"},
"Coffee":{"Level":"399.2023%","Temperature":"34"},
"Chocolate":{"Level":"109.2023%","Temperature":"14"}
}
I'm new and my thinking is get the product value in array and again use foreach loop to find the others value? .
Here's one possibility:
$jsonArray = '[{"Level":"77.2023%","Product":"Milk","Temperature":"4"},
{"Level":"399.2023%","Product":"Coffee","Temperature":"34"},
{"Level":"109.2023%","Product":"Chocolate","Temperature":"14"}]';
$output = array();
foreach (json_decode($jsonArray, true) as $row) {
$product = $row['Product'];
$output[$product] = $row;
unset($output[$product]['Product']);
}
echo json_encode($output);
Output:
{"Milk":{"Level":"77.2023%","Temperature":"4"},
"Coffee":{"Level":"399.2023%","Temperature":"34"},
"Chocolate":{"Level":"109.2023%","Temperature":"14"}
}
Demo on 3v4l.org
This made some trick
$a = '[{"Level":"77.2023%","Product":"Milk","Temperature":"4"},
{"Level":"399.2023%","Product":"Coffee","Temperature":"34"},
{"Level":"109.2023%","Product":"Chocolate","Temperature":"14"}]';
$newAr = array();
foreach(json_decode($a,true) as $key=>$value)
{
$newAr[$value['Product']] = array(
'Level' => $value['Level'],
'Temperature' => $value['Temperature'],
);
}
There are many ways to perform this with Loops in PHP. Other answers demonstrate it accurately. I would also suggest to integrate some form of Error handling, data validation/filtering/restriction in your code to avoid unexpected results down the road.
For instance, json_decode(), either assigned to a variable pre-foreach or straight in the foreach() 1st argument will just raise a warning if the original json is not valid-json, and just skip over the foreach used to construct your final goal. Then if you pass the result (that may have failed) directly to your next logic construct, it could create some iffy-behavior.
Also, on the concept of data-validation & filtering, you could restrict the foreach(), or any other looping mechanism, to check against a Product_List_Array[Milk,Coffee,Chocolate], using if(in_array() ...) so the final/goal object only contains the expected Products, this, in the case the original json has other artifacts. Filtering the values can also increase stability in restricting, for example, Temperature to Float.
I need to compare 2 different format arrays. The goal is to print from file1 only that rows which contain value from file2.
I suppose that I have to load both files into 2 arrays and compare it. I tried array_intersect(), in_array() and array_key_exists(), nothing works for me.
Here is the example of data files:
File 1:
2.26.81.0,4,10146128,10165054
82.132.227.75,7,10146130,10166530,10166093
91.206.0.35,10,10150898,10165809
88.145.18.102,3,10169097,10141126,21729395
File 2:
10146128
10146130
Result should looks like this:
2.26.81.0,4,10146128,10165054
82.132.227.75,7,10146130,10166530,10166093
I have loaded both files in 2 arrays and I need to compare them now
$bought = fopen('f_data.csv', 'r');
$visited = fopen('l_data.csv', 'r');
$line = fgets($bought);
while(! feof($bought)) {
$line = fgets($bought);
$bought_f[] = $line;
}
$line2 = fgets($visited);
while(! feof($visited)) {
$line2 = fgets($visited);
$visited_f[] = $line2;
}
The functions you used didn't work because you converted the first file in an array putting each line into an array element, but since each line not a value but a list of values you should create a two-dimensional array (an array of arrays), so each array element contains just a value. For example you can do that using file() and explode():
// getting an array with an element for each line
$file1=file("file1.csv");
$length=count($file1);
// converting each line in an array of the comma-separated values
for ($i=0;$i<$length;$i++) {
$file1[$i]=explode(",",$file1[$i]);
}
//for file2 using file() is enough as each line only contains one value
$file2=file("file2.csv");
In this way $file1[0][0] is2.26.81.0, $file1[0][1] is 4, $file1[0][2] is 10146128 and so on. Then, you have several options, the most basic one is using a double loop:
foreach ($file1 as $line) {
foreach ($file2 as $value) {
// code for checking if $value is contained in $line and store/print the result
}
}
Depending of what you need using in_array() for comparison and implode() for converting the line back to a comma-separated string would do the job.
Also note that if the first file can contain several values of the second file in the same line you can get duplicate results, in that case the solution would be stop checking the values of the second array as soon as you get a match.
I am trying to process the submitted results for a form, containing data for a number of employees. The form inputs have names like "employees[1]_firstName" which needs to map to the PHP variable $companydata->employees[1]->firstName
When populating the $_POST array, PHP sees square brackets, and tries to make a multi-dimensional array, but gets it wrong (ignoring everything after the opening bracket)
This replicates $_POST but without the corrupted array keys: Note that I've taken out a foreach loop to simplify the question.
$post_data = explode('&', file_get_contents("php://input"));
// Result: $post_data = array('employees%5B1%5D_firstName=Timothy'
list($key, $value) = explode('=', $post_data[0]);
$key = urldecode($key);
$value = urldecode($value);
// Result: $key = 'employees[1]_firstName', $value = 'Timothy'
However things go wrong when I try to use variable variables:
$post_key_parts = explode('_', $key);
// Result: $post_key_parts = array([0] => 'employees[1]', [1] => 'firstName')
$Companydata->$post_key_parts[0]->$post_key_parts[1] = $value;
// Expected result: Element [0] in array $employees => 'Timothy'
The actual result is a variable with square brackets in its name '$employees[0]',
and no change to the $employees array. Putting curly brackets round the {$post_key_parts[0]} doesn't help.
I am trying to find a flexible solution that will also work for names of different lengths eg: employees[0]_address_lines[2] or employees[0]_addresses[1]_postcode
I'm happy to avoid the sin of variable variables, but I can't think of an elegant way to do it with regexes or something like that.
I would suggest you change the inputs' names. To make use of the built-in features of PHP. [] creates an array for you, use arrays then, as you are intended to use them.
I had the same problem and came up with this:
//HTML part
<input name="employee_firstName[]">
<input name="employee_address[]">
//PHP part
<?php
$info = array("firstName", "address")
foreach ($info as $i) {
foreach ($_POST["employee_".$i] as $k => $v) {
$companydata->employees[$k]->$i = $v;
}
}
?>
NOTE I don't think you can do this for things like employees[0]_address_lines[2]. Or maybe try employees[0][address_line][] and use it as an array, but I'm not sure that works.
How can you do this? My code seen here doesn't work
for($i=0;i<count($cond);$i++){
$cond[$i] = $cond[$i][0];
}
It can be as simple as this:
$array = array_map('reset', $array);
There could be problems if the source array isn't numerically index. Try this instead:
$destinationArray = array();
for ($sourceArray as $key=>$value) {
$destinationArray[] = $value[0]; //you may want to use a different index than '0'
}
// Make sure you have your first array initialised here!
$array2 = array();
foreach ($array AS $item)
{
$array2[] = $item[0];
}
Assuming you want to have the same variable name afterwards, you can re-assign the new array back to the old one.
$array = $array2;
unset($array2); // Not needed, but helps with keeping memory down
Also, you might be able to, dependant on what is in the array, do something like.
$array = array_merge(array_values($array));
As previously stated, your code will not work properly in various situation.
Try to initialize your array with this values:
$cond = array(5=>array('4','3'),9=>array('3','4'));
A solution, to me better readable also is the following code:
//explain what to do to every single line of the 2d array
function reduceRowToFirstItem($x) { return $x[0]; }
// apply the trasnformation to the array
$a=array_map('reduceRowTofirstItem',$cond);
You can read the reference for array map for a thorough explanation.
You can opt also for a slight variation using array_walk (it operate on the array "in place"). Note that the function doesn't return a value and that his parameter is passed by reference.
function reduceToFirstItem(&$x) { $x=$x[0]; }
array_walk($cond, 'reduceToFirstItem');
That should work. Why does it not work? what error message do you get?
This is the code I would use:
$inArr;//This is the 2D array
$outArr = array();
for($i=0;$i<count($inArr);$i++){
$outArr[$i] = $inArr[$i][0];
}