如果PHP具有来自另一个数组的特定字符串,则获取数组值

时间:2014-01-10 20:06:32

标签: javascript php arrays

我有多个文件,我试图合并为1个单个文件。每个文件都有类似的内容:

var nr = ['1.02.3.1','1.02.3.4'];
var p = [{"ip":"1.02.3.1","parents":["1.02.3.0","1.1.2.2"},{"ip":"1.04.1.1","parents":["1.1.30.0","1.15.2.2"}];

请记住,我现在正尝试将信息解析为文本。

不同的文件有不同的IP,(IP是列表中的值。我一次合并2个文件。对于nr数组,这很容易。我所做的就是删除不必要的数据让我离开 '1.02.3.1', '1.02.3.4' 然后我把字符串分解成一个数组。我将数组与其他文件的数组合并,取出重复数据,内爆数据,添加“var nr = [”和“];”

我在下一部分遇到了麻烦。我想用“nr”交叉检查“p”。使用合并的“nr”数组。如果“nr”的任何值与“p”的ip匹配,则保存将ip写入名为“nrp”的新数组,并将该ip的父项列表保存到统一的“p”数组中。此外,我想要删除“nr”未列出的ip和父ips。

例如,我将ip表示为字母

档案A:

var nr = ['A','B','C'];
var p = [{"ip":"A","parents":["J","K","L"]},{"ip":"B","parents":["J","K","L"]},{"ip":"C","parents":["K","L","M"]} ];

档案B:

var nr = ['A','C','D'];
var p = [{"ip":"A","parents":["J","K","L"]},{"ip":"D","parents":["N","O","P"]},{"ip":"C","parents":["K","L","M"]} ];

文件合并:

var nr = ['A','B','C','D'];
var p = [{"ip":"A","parents":["J","K","L"]},{"ip":"B","parents":["J","K","L"]},{"ip":"D","parents":["N","O","P"]},{"ip":"C","parents":["K","L","M"]}];
var nrp = ['J','K','L','N','O','P','M'];

到目前为止我的方法: 这是在我有数组的数据之后。

$consolidatedNR = ['A','B','C','D'];
$consolidatedP = [{"ip":"A","parents":["J","K","L"]},{"ip":"B","parents":["J","K","L"]},{"ip":"D","parents":["N","O","P"]},{"ip":"C","parents":["K","L","M"]}];

foreach($consolidatedP as $key5 => &$string5){
            foreach($consolidatedNR as $key2 => &$ip){
                if($string5 contains "'ip':$ip"){
                    array_push($content4, $ip);
                }
                else{
                    unset($consolidatedP[$key5]);
                }
            }
        }

1 个答案:

答案 0 :(得分:1)

您拥有的阵列是可接受的JSON格式。您可以从字符串中删除JavaScript分配,将字符串分解为两行,然后使用json_decode()将行转换为PHP数组。

这应该适合你:

修改:我已编辑并测试了此代码。

<?php

$str = <<<EOF
var nr = ['1.02.3.1','1.02.3.4'];
var p = [{"ip":"1.02.3.1","parents":["1.02.3.0","1.1.2.2"]},{"ip":"1.04.1.1","parents":["1.1.30.0","1.15.2.2"]}];
EOF;

$str = str_replace(array("var nr = ", "var p = ", ";"), "", $str);
$str = str_replace("'", "\"", $str);
$str = explode("\n", $str);

$parents_list = array();
$ip_list = array();

$nr = json_decode($str[0], true);
$p = json_decode($str[1], true);
echo "<pre>";
foreach($p as $p_list) {
    if(in_array($p_list['ip'], $nr)) {
        array_push($ip_list, $p_list['ip']);
        $parents_list = array_merge($p_list['parents'], $parents_list);
    }
}

echo "Parents list:<pre>";
print_r($parents_list);
echo "</pre>IP list:<pre>";
print_r($ip_list);
echo "</pre>";

?>