子串和爆炸的PHP难度

时间:2014-04-26 23:18:16

标签: php arrays date substring preg-match-all

我输入了一些产品作为“id”参数,有关购买,状态和购买用户的信息,您可以在此输入示例中看到。

{"id":2694301,"state":3,"timeout":25,"date":"2014-04-27 00:32:37","date_timeout":"2014-04-27 01:00:02","user":"wolf_359","purchase":341.52},{"id":34017,"state":1,"timeout":10,"date":"2014-04-27 01:59:34","date_timeout":"2014-04-27 01:00:02","user":"mik10","purchase":217.90},{"id":12317,"state":2,"timeout":5,"date":"2014-04-27 03:51:31","date_timeout":"2014-04-27 01:00:02","user":"assemblyuser","purchase":1321.17};

我正在尝试的是只获得一个产品,订购所有信息,知道身份证。 这意味着,例如,如果我知道我的Id是34017,我只想显示这一行忽略其他人:

{"id":34017,"state":1,"timeout":10,"date":"2014-04-27 01:59:34","date_timeout":"2014-04-27 01:00:02","user":"mik10","purchase":217.90}

所以我要求帮助的原因是我不知道是否有任何其他可能性使用子串并爆炸数据导致这看起来非常复杂。这就是我所做的:

preg_match_all('/{"id":2694017/', $page, $matches, PREG_OFFSET_CAPTURE); 
$firstkey = $matches[0][0][1];
$page = substr($page, $firstkey, 210);
$values = explode('/:,', $page);
$value1 = $values[1];
$value2 = $values[2];
$value3 = $values[3];
$value4 = $values[4];
$value5 = $values[5];
$value6 = $values[6];
$value7 = $values[7];

在第一个通道中,我获得了{所在字符串中的位置。然后我用一个子字符串剪切寄存器加上下一个字节,防止用户名可能很长。之后,由于我知道我感兴趣的寄存器在接下来的7个冒号中,我只是爆炸了。

2 个答案:

答案 0 :(得分:1)

使用json_decode函数太简单了; 确保您拥有正确的数据格式。在您的情况下,您需要使用“ [] ”包装输入数据 只需看看代码:

$inputData = '[
{"id":2694301,"state":3,"timeout":25,"date":"2014-04-27 00:32:37","date_timeout":"2014-04-27 01:00:02","user":"wolf_359","purchase":341.52},
{"id":34017,"state":1,"timeout":10,"date":"2014-04-27 01:59:34","date_timeout":"2014-04-27 01:00:02","user":"mik10","purchase":217.90},
{"id":12317,"state":2,"timeout":5,"date":"2014-04-27 03:51:31","date_timeout":"2014-04-27 01:00:02","user":"assemblyuser","purchase":1321.17}
]';

$products = json_decode($inputData);
$productId = 34917; // product id wich you want to show;

$result = array();
foreach($products as $product) {
  if ($product['id'] == $productId) {
     $result = $product;
     break;
  }
}


var_dump($result); // here you will data for product you want.

答案 1 :(得分:0)

正如您对问题的评论中所建议的那样......请不要使用Regex来解析JSON字符串并使用json_decode代替。

$id = 2694017;
$input_arr = json_decode($input);
$needed_row = null;
foreach($input_arr as $row)
{
  if($row->id == $id)
  {
    $needed_row = $row;
    break;
  }
}

if(isset($needed_row)){ ... }

如果您想访问输入中的多个ID,您可能会创建一个数组,其中ID是foreach循环中此附加数组的键。