平面文件从数组中选择值

时间:2014-05-19 07:38:55

标签: php arrays array-difference array-intersect

我有平面文件,数据用","我需要将值与url进行比较,并仅显示具有相同url值的值

不需要PHP的CSV功能,我想比较并获得结果,如果与url的值最终相同时

csv有4个值,价格,大小,宽度和高度

URL值,发送其他值,但顺序相同(价格,大小,宽度和高度),例如在网址中我使用字符串index.php发送此信息?price = 100& size = 100& width = 200& ;身高= 300 ......等等

例如:

<?php

    $csv_file=file("test.csv");

    for($i=0;$i<sizeof($csv_file);$i++) {

    $exp_csv=explode(",",$csv_file[$i]);

    foreach($exp_csv as $exp_csv2) {
        $csv_end_values[]=$exp_csv2
    }

}


/// By Other side the url 

$exp_url="100,30,400,500";

$exp_url_values=explode(",",$exp_url);


foreach($exp_url_values as $exp_url_values2) {
    $url_end_values[]=$exp_url_values2;
}


/// Finally we have 2 arrays one array with all values we 
get in bucle for csv and by other side values get from url , 
now we need compare url values with values of csv , 
for example if in the url we have only 2 values and no 4 show 
only results with the same of 2 values from url and compare 
in the same order , if when compare the values no the same all , get 0 results 


/// For example values from URL 100,,200,, 
if in csv exists one row with the values 100 and 200 
in the same order show as result and if no , no show 


/// In this point i try use array_difference , 
but no works , because i need compare all values i send by 
url and in the same order 


$aa = array_diff($url_end_values,csv_end_values);


$num_results=0;

foreach($aa as $bb) {
    $num_results++;
}


if ($num_results==0) {
    print "We get Results";
}
else {
    print "No Results";
}

?>

2 个答案:

答案 0 :(得分:1)

使用fgetcsv(http://php.net/fgetcsv)读取CSV文件而不是普通文件方法。您将获得数组格式,从URL查询字符串中进行比较会更容易。

答案 1 :(得分:0)

这是基于我的理解你真正想要的。

$link1 = "index.php?price=150&size=200";
$link2 = "index.php?price=100&size=100";

// separate the string by ampersand to get the get parameters.
$link1ParamsRaw = explode('&',substr(stristr($link1, '?'),1)); // the second param removes all strings from start to ?
$link2ParamsRaw = explode('&',substr(stristr($link2, '?'),1));

$link1Params = array();
$link2Params = array();

foreach($link1ParamsRaw as $param) {
    $param = explode('=',$param); // separate key from value                 
    $link1Params[$param[0]] = $param[1]; // assuming all keys have values
}

foreach($link2ParamsRaw as $param) {
    $param = explode('=',$param); // separate key from value                 
    $link2Params[$param[0]] = $param[1]; // assuming all keys have values
}

$differences = array_diff_assoc($link1Params, $link2Params);

var_dump($differences);