Query arrays using php - php

I have an array of imported data:
array(3) {
[1234]=>
array(2) {
["item"]=>
string(6) "scotch"
["type"]=>
string(6) "Spirit"
}
[5678]=>
array(2) {
["item"]=>
string(4) "wine"
["type"]=>
string(7) "Vintner"
}
[9012]=>
array(2) {
["item"]=>
string(11) "soft drinks"
["type"]=>
string(3) "Pop"
}
}
I'm trying to make it say "Its in the Spirit section under code 1234"
I'm new to php so not sure I'm writing the for loop if function correctly. I keep getting "We are out of stock". Man I need a whisky. Help please
my code:
<?php
$row = 1;
$sheet1 = [];
if (($handle = fopen("sheet1.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$sheet1[$data[0]] = [];
$sheet1[$data[0]]['item'] = $data[1];
$sheet1[$data[0]]['type'] = $data[2];
$row++;
}
fclose($handle);
}
var_dump($sheet1);
$string = 'Where is scotch in shop';
echo $string;
$words = explode(' ', $string);
print_r($words);
for ($i = 0; $i < count($words); ++$i) {
if (isset($sheet1[$words[$i]]['item'])) {
echo "Its in the ".$sheet1[$words[$i]]['type']." section marked
under code ".$sheet1[$words[$i]]['key'];
}
}
echo "We are out of stock";
?>

If you change it to a foreach and then check for the existance of the word using in_array() it all looks a litle easier to understand.
foreach ($sheet1 as $key=>$sheet) {
if ( in_array($sheet['item'], $words) ) {
echo "Its in the {$sheet['type']} section marked under code $key";
}
}
Result
Its in the Spirit section marked under code 1234

Related

How to exclude NULL results in a .txt file and display them in php?

I read a csv file that contains these values :
; ;WH;391;M;9353970157191;A1124;0010;TU;1; ;7/1/2019;0;0;
; ;WH;391;M;9353970157214;A1119;0090;TU;1; ;7/1/2019;0;0;
....
At the end I get a .txt file which is like this:
MMXC1_|A0391|9353970395487|0|0
MMXC1_|A0391| |1|0 //$SKU_EAN NULL
MMXC1_|A0391|9353970394879|4|2
...
But sometimes the $SKU_EAN is NULL because it doesn't have a corresponding sku_code
I would like to exclude lines where the $SKU_EAN is NULL from my .txt file and display them on the screen with the sku_code, and the number of the corresponding line in the csv file, how can I do that?
$resultat = mysqli_query($bdd, "SELECT trim(concat(concat(SKU_ITEM_VARIANT,'_'),trim(SKU_SIZE)))as sku_code , SKU_EAN FROM dwh_dev.dwh_d_sku");
while ($donnees[] = mysqli_fetch_assoc($resultat)) {
// var_dump($donnees); //array(1) { [0]=> array(2) { ["sku_code"]=> string(13) "A1101_0090_TU" ["SKU_EAN"]=> string(13) "9346799868270" } } array(2) { [0]=> array(2) { ["sku_code"]=> string(13) "A1101_0090_TU" ["SKU_EAN"]=> string(13) "9346799868270" }....
}
$constante = "MMXC1_";
$temp = array_column($datas_mag, 'MAGCOD', 'MAGAS400');
$temp2 = array_column($donnees, 'SKU_EAN', 'sku_code');
if (($handle = fopen("$nomcsv", "r")) !== FALSE) {
$firstLine = true;
while (($data = fgetcsv($handle, 1000000, ";")) !== FALSE)
{
if(!$firstLine) {
$EAN = 'A'.$temp[$data[3]];
$SKU_EAN = $temp2[$data[6].'_'.$data[7].'_'.$data[8]];
var_dump($SKU_EAN); //string(13) "9353970395487" string(13) "9346799046166" NULL NULL string(13) "9346799046756"...
$data_final[] = $constante.'|'.$EAN.'|'.$SKU_EAN.'|'.$data[12].'|'.$data[13];
var_dump($data_final); //array(1) { [0]=> string(30) "MMXC1_|A0391|9353970395487|0|0" }
}
$firstLine = false;
}
}
$cheminfile = "//alcyons/IT/PhotoShoot/retail/CSV/TXT_Finaux/MMX".date('His').".txt";
$fp = fopen("$cheminfile", "w");
foreach($data_final as $data){
fwrite($fp,$data."\n");
}
fclose($fp);
Try this
I've assumed that your comment around $SKU_EAN are individual example values, so adding the following line should skip the iteration where this value is null.
if(is_null($SKU_EAN)) continue;
Full code:
$i = 1;
while(($data = fgetcsv($handle, 1000000, ";")) !== FALSE) {
$i++;
if(!$firstLine) {
$EAN = 'A'.$temp[$data[3]];
$SKU_EAN = $temp2[$data[6].'_'.$data[7].'_'.$data[8]];
if(is_null($SKU_EAN)) {
echo 'Can\'t find SKU_EAN for iteration number: ' . $i . '<br />';
continue;
}
$data_final[] = $constante.'|'.$EAN.'|'.$SKU_EAN.'|'.$data[12].'|'.$data[13];
}
$firstLine = false;
}

Cannot use string value from array in PHP

I have an array with two string values, but cannot use one of them. If I use
var_dump($array[0]);
it's result is
array(2) { ["id"]=> string(2) "01" ["name"]=> string(10) "Aquamarine" }
but
var_dump($array[0]["id"]);
shows me NULL.
I've tried changing "id" to sth else, tried using ' instead of ", with the same effect, strlen($array[0]["id"]) also returns 0. The second one ("name") works just fine.
Update:
The array is initalized with this code:
$handle = #fopen("stones.csv", "r");
if ($handle) {
while (($row = fgetcsv($handle, 4096, ';')) !== false) {
if (empty($fields)) {
$fields = $row;
continue;
}
foreach ($row as $k=>$value) {
$array[$i][$fields[$k]] = $value;
}
$i++;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
var_dump($array[0]);
var_dump($array[0]["id"]);
var_dump(array_keys($array[0]));
So there are no modifications between dumps, last three rows return this
array(2) { ["id"]=> string(2) "01" ["name"]=> string(10) "Aquamarine" } NULL array(2) { [0]=> string(5) "id" [1]=> string(4) "name" }
Now I see that there are some invisible characters in the "id" key, so the next question is how to get rid of them?
trim the key using builtin "trim" function. ref: http://php.net/manual/en/function.trim.php
$handle = #fopen("stones.csv", "r");
if ($handle) {
while (($row = fgetcsv($handle, 4096, ';')) !== false) {
if (empty($fields)) {
$fields = $row;
continue;
}
foreach ($row as $k=>$value) {
$array[$i][trim($fields[$k])] = $value;
}
$i++;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
var_dump($array[0]);
var_dump($array[0]["id"]);
var_dump(array_keys($array[0]));

How can I split a huge array into chunks?

I am parsing about 500.000 entries into an array $properties:
$properties = array();
$handle = fopen($file_path, "r");
if ($handle) {
while (($str = fgets($handle)) !== false) {
if (strlen($str) && $str[0] == '#') {
$pdate = substr($str, 1);
$date = rtrim($pdate);
$formatted = DateTime::createFromFormat('* M d H:i:s T Y',$date);
}
$str = rtrim ($str, "\n");
$exp = explode ('=', $str);
if(count($exp) == 2){
$exp2 = explode('.', $exp[0]);
if( count($exp2) == 2 ) {
if($exp2[1] == "dateTime"){
$s = str_replace("\\","",$exp[1]);
$d = strtotime($s);
$dateTime = date('Y-m-d H:i:s', $d);
$properties [$exp2[0]][$exp2[1]] = $dateTime;
} else {
$properties [$exp2[0]][$exp2[1]] = $exp[1];
}
} else {
$properties [$exp[0]] = $exp[1];
}
}
}
fclose($handle);
} else {
echo "error";
}
This is working well so far. But I need to split the array into chunks, because otherwise the array is too big to work with it:
$properties_chunk = array_chunk($properties,10000,true);
But now I have the problem that the $properties_chunk array is not created. The system crashes. This is too much. But what can I do now?
The array should look like this in the end:
array(4) {
[0]=>
array(10000) {
["12345"]=>
array(5) {
["dateTime"]=>
string(19) "2016-10-12 19:46:25"
["fileName"]=>
string(46) "monkey.jpg"
["path"]=>
string(149) "Volumes/animals/monkey.jpg"
["size"]=>
string(7) "2650752"
}
["678790"]=>
array(5) {
["dateTime"]=>
string(19) "2016-10-12 14:39:43"
["fileName"]=>
string(45) "elephant.jpg"
["path"]=>
string(171) "Volumes/animals/elephant.jpg"
["size"]=>
string(7) "2306688"
}
... and so on.
If you use array_splice the items will be moved from the input array to the resulting array.
This should mean the memory use should stay the same-ish.
This will do the same as array_chunk but hopefully be less memory hungry.
$arr = [1,2,3,4,5,6,7,8,9,10];
$n = 10000;
$count = (count($arr)/$n)-1; // do not splice the last items in loop
For($i=0; $i<$count; $i++){
$res[] = array_splice($arr, 0,$n);
}
$res[] = array_splice($arr, 0,count($arr));
// here we splice the last items from arr to $res.
// Notice how we splice count($arr) instead of $n.
// If count($arr) == $n we could have done it in the loop.
// But if we assume they are not, array_splice in the loop will create empty items. This line will not.
Var_dump($res, $arr); // $res has all values, $arr is empty
https://3v4l.org/XDpdI

php csv import data but in one array

Data from CSV like below, just one column
| BeKwX8iN3wzHDvCaxBD1 |
| 3rPB9t6EF3RGla28YbLE |
| OAYRwbrkctcVbrXaaTef |
| N8lxYdvx47FI7eYt5FUX |
| zwtRdHr3aYYnX9avcMjX |
.....
file content look: https://drive.google.com/a/hiiir.com/file/d/0B4ZVHStLEPq3bklUUHkzbDN1MkE/view?usp=sharing
The code
$row = 1;
if (($handle = fopen($serial['tmp_name'], "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
the issue is that when I print $num, I got int(1), because they are all in one array()
array(1) {
[0]=>
"BeKwX8iN3wzHDvCaxBD1
3rPB9t6EF3RGla28YbLE
OAYRwbrkctcVbrXaaTef
N8lxYdvx47FI7eYt5FUX
zwtRdHr3aYYnX9avcMjX"}
I know fgetcsv() controll by $delimiter, and this case is ,,but it not suitable for my case. Is it possible to separate by 20 Characters?
You cannot use fgetcsv to read a fixed length CSV, you have to do it on you own.
[EDIT]
The problem here was not a CSV problem, it was caused by end line "\r". See comments below to deal with it.
[/EDIT]
In your case, use the delimiter params :
$data = fgetcsv($handle, 1000, "|")
Your code exampled :
<?php
if (($handle = fopen('csv.txt', "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "|")) !== FALSE) {
array_pop($data);
array_shift($data);
var_dump($data);
}
fclose($handle);
}
Result :
array(1) {
[0]=>
string(22) " BeKwX8iN3wzHDvCaxBD1 "
}
array(1) {
[0]=>
string(22) " 3rPB9t6EF3RGla28YbLE "
}
array(1) {
[0]=>
string(22) " OAYRwbrkctcVbrXaaTef "
}
array(1) {
[0]=>
string(22) " N8lxYdvx47FI7eYt5FUX "
}
array(1) {
[0]=>
string(22) " zwtRdHr3aYYnX9avcMjX "
}

Reading from CSV and merging content in rows into an array

pastebin link: http://pastebin.com/4YCdbrsP
Input CSV format,
number | itemid
1001, 121212
1001, 12991
1042, 99878
1042, 89776
1042, 87777
1045, 11010
1046, 22299
1049, 9875
Expected Output
[1001 => {121212,12991}]
[1042 => {99878, 89776, 87777}]
[1045 => {11010}]
[1046 => {22299}]
[1049 => {9875}]
I am trying to read each line from a CSV file which has contents as specified above (two columns, each row containing "number" as the first column and an associated "itemid" as the second column.
If the next line has the same "number" then, I would like its corresponding "itemid" to be pushed to an array. Repeat this, if the next line(s) have the same "number".
Following is where I have gotten so far.
$row = 0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE && $row < 8) {
$sku = $data[0];
$upc = $data[1];
$skuUpcList = array($sku => array());
array_push($skuUpcList[$sku], $upc);
$row++;
while(($data = fgetcsv($handle, 1000, ",")) !== FALSE && $row < 8) {
if($data[0] == $sku) {
array_push($skuUpcList[$sku], $data[1]);
$row++;
} else {
$sku = $data[0];
$upc = $data[1];
$skuUpcList = array($sku => array());
array_push($skuUpcList[$sku], $data[1]);
$row++;
}
$skuUpcList = array_unique($skuUpcList);
var_dump($skuUpcList);
echo '<br>';
}
}
=== Output of the above script ===
array(1) { [1001]=> array(2) { [0]=> string(6) "121212" [1]=> string(5) "12991" } }
array(1) { [1042]=> array(1) { [0]=> string(5) "99878" } }
array(1) { [1042]=> array(2) { [0]=> string(5) "99878" [1]=> string(5) "89776" } }
array(1) { [1042]=> array(3) { [0]=> string(5) "99878" [1]=> string(5) "89776" [2]=> string(5) "87777" } }
array(1) { [1045]=> array(1) { [0]=> string(5) "11010" } }
array(1) { [1046]=> array(1) { [0]=> string(5) "22299" } }
array(1) { [1049]=> array(1) { [0]=> string(4) "9875" } }
As you can see, even though the script runs fine, I am trying to make sure that the script echos each "number" only once but, as per the above output the "number" 1042 appears three times.
I have tried to move the var_dump() statement outside the 2nd while loop but, it doesn't seem to help.
Any help regarding this would be helpful.
pastebin link: http://pastebin.com/4YCdbrsP
$skuUpcList = array();
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$skuUpcList[$data[0]] []= $data[1];
}
This seems to work quite nicely:
<?php
$handle = fopen("xxx.csv", "r");
$row = 0;
$skuUpcList = array();
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE && $row < 8) {
$sku = $data[0];
$upc = $data[1];
if ( array_key_exists($sku, $skuUpcList) ) {
$skuUpcList[$sku][] = $upc;
} else {
$skuUpcList[$sku] = array($upc);
}
$row++;
}
print_r( $skuUpcList );

Categories