php, get values from matrix (array) - php

I have Matrix and how get value from there?
The data obtained from a file, so that the matrix can be of different sizes
Thanks

Hypothetically (because the question is vague), if you read the contents in and have the results stored in a two-dimensional array, then you would use brackets to find the cell value. For example, here's reading in the contents into a multidimensional array called $matrix:
$contents = file_get_contents("myfile.csv");
$splitlines = explode("\n",$contents);//split the contents into rows
$matrix = array();
foreach($splitlines as $line){
$row = explode(",",$line);//split each line into columns
$matrix[] = $row;//add the array of columns as a new row in the matrix
}
now address any of the values in the matrix:
$samplevalue = $matrix[2][1]; //addresses the third row, second column.

Related

incremented json keys, parsing CSV

I'm using mailparser.io to parse a .csv attachment and make an http post to another cloud service. The problem is the json received is not an associative array but rather key values are incremented:
First_Name::1 = "John"
First_Name::2 = "Sally"
First_Name::3 = "Kenneth"
Last_Name::1 = "Smith"
Last_Name::2 = "Johnson"
Last_Name::3 = "Cline"
Using PHP, how can I reformat this into a usable json associative array and retain the index, something like:
{"Record":"1","First_Name":"John","Last_Name":"Smith"}
{"Record":"2","First_Name":"Sally","Last_Name":"Johnson"}
{"Record":"3","First_Name":"Kenneth","Last_Name":"Cline"}
The number of rows will vary, but the columns will always be the same. So I assume I can count the number of key:value pairs and divide by the number of columns. My example would provide 6 pairs, dividing by 2 columns would yield 3 sets. Create an incremental loop and retrieve/build a usable json string.
$count = count($string);
$rows = $count/2;
$index = 0;
while($index <= $rows) {
**get First_Name::1, Last_Name::1 and build json**
$index++;
}
Yes, I realize mailparser will create an http post for each row in a csv, but it won't keep them in the original row order and I need to preserve that.
I've been able to tweak some settings in mailparser and now am receiving it as
"Record":[{"0":"John","1":"Smith"},
{"0":"Sally","1":"Smith"},
{"0":"Kenneth","1":"Cline"}
]

Return row from an array if contains a value from another array with a different value format

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.

Put values in array and Get values using foreach

e.g. I have this Product Id values 31,32 from database. I want to put them on array. So, I can use the values for foreach.
What I want to achieve:
I want to get the stock of each product from database according to the given values (31,32).
What I tried:
$product_values = '31,32'; //this values can be different, sample values only
$arr_product_values = array();
$arr_product_values[] = $product_values;
foreach ($arr_product_values as $prod_id) {
echo $prod_id;
}
Expected output:
31 & 32
$arr_product_values[] = $product_values;
That doesnt mean you have a new array with those 2 values now. You just took a comma separated string and assigned it to an array element, that doesnt make it an array itself.
$arr_product_values = array(31,32);
Does.
Now you can loop over it

How can I filter a PHP string to only display a unique result?

I have a CSV file that I am outputting to a table via PHP. The CSV data appears like this:
0072534,800:fixed:9.9900:0072534|6500:fixed:9.9900:0072538|2100:fixed:9.9900:0072537
0072538,800:fixed:9.9900:0072534|6500:fixed:9.9900:0072538|2100:fixed:9.9900:0072537
0072537,800:fixed:9.9900:0072534|6500:fixed:9.9900:0072538|2100:fixed:9.9900:0072537
I am struggling to work out how I can get the second CSV column to only display the data relevant to the ID in the first CSV column. The desired result would be:
0072534, 800
0072538, 6500
0072537, 2100
(The first part of the second column is the data I am after, i.e. the the data before the first ':' )
Does that make sense and can someone suggest a solution? Thank you!!
You could iterate over each row (however you're parsing your CSV file), and further iterate over each CSV column - exploding the second column.
This is assuming that you want to get the beginning value after each | character, dependent on the row number. If I am misunderstanding, let me know - your question could be far clearer.
For example, something like this:
$count = 0;
$final = array();
foreach ($rows as $row) {
$columns = explode(",", $row);
$column2 = explode("|", $columns[1]);
$length = strpos($column2[$count], ':');
$column2 = substr($column2[$count], 0, $length);
$final[] = array($columns[0], $column2);
$count++;
}

PHP spontaneously creates associative array where indexed array is required - using PHP arrays with Highcharts

I'm using PHP to retrieve data from an SQL database to produce a stacked column chart in Highcharts. The idea is that I'm taking the following piece of code to retrieve values from my database. This code should generate an array which then gets encoded to JSON and passed to Highcharts; this code produces a single 'part' of a stacked column, and the index determines which vertical bar that part is in. (So in http://www.highcharts.com/demo/column-stacked, the index would represent which fruit, and the data in this series would represent one person/color.)
The issue is that when I run this code, instead of ending up with an indexed array of data grouped by category, such as
[12,13,14,15] where each item is a category, I end up with an associative array where the indexes I specified in the code are turned into a string key.
{"1":13,"0":12,"3":14, "2":13, "5":15}
Because my indexes are being interpreted as associative keys and not as the indexed locations of the data inside the array, the data is now being added to locations in the order that I retrieved the data, and not assigned to a location in the array based on the index I give. Highcharts assigns categories based on location in the array, and not on key, so all my data ends up in the wrong categories.
Is there a way to get PHP to treat my carefully collected indexes as indexes and not as keys, and add my data points in the location in the array indicated by the indexes? I'm kind of new to PHP, and Java and C++ - the languages I've worked with before - don't have associative arrays, so any help you can give me in explaining and fixing this undesired behavior would be much appreciated.
Code below.
$variable indicates what the data is being sorted into categories by, and $r is the variable representing the array of the SQL query, so $r['variable'] is the category of this data point, and $r['amount'] is the data point itself.
$found = -1;
//if this is the first set of data being collected
if (count($category['data']) == 0){
$category['data'][0] = $r[$variable];
$series1['data'][0] = floatval($r['amount']);
$count++;
$times1[0]++;
}
//if it's not the first set of data, find out if this category has been used before
else {
for ($x = 0; $x < count($category['data']); $x++){
if ($r[$variable] == $category['data'][$x]){
$found = $x;
break;
}
}
// if that category does not already exist, add it, and add the data
if ($found == -1) {
$times1[$count]++;
$category['data'][$count] = $r[$variable];
$series1['data'][$count] = floatval($r['amount']);
$count++;
}
else { //otherwise, add its data to the data already in the current category. This will eventually yield an average, with $times1[] as the divisor
$times1[$found]++;
$series3['data'][$found] = floatval((floatval($series3['data'][$found]) + floatval($r['amount'])));
}}
Go through with below code hope it will give some idea to resolve your problem --
<?php
$jsonstring = '{"1":13,"0":12,"3":14, "2":13, "5":15}';
$tempArr = json_decode($jsonstring, true);
asort(tempArr); // for sorting the array --
//run another foreach to get created an array --
$finArr = array();
foreach(tempArr as $key=>$val){
$finArr[] = $val;
}
$requiredjsonString = json_encode(finArr); // it will return your required json Array [12,13,14,15]
?>
Edit: I advice also set JSON_NUMERIC_CHECK flag in json_encode();

Categories