Reputation: 596
I need to take out some info from a string. What I need to get is the data from the second value from the second line for example, anyway depending of the user I can need the data from the third line or another one. Is it possible to make a query to get this info?
Regards
$searchLine = "13";
$str = "[
[1, u'G4622', u'2300866', u'1111', u'zzzz'],
[2, u'G4622', u'2300873', u'2222', u'zzzz'],
[13, u'G4626', u'2300975', u'3333', u'zzzz'],
]";
$str = str_replace('u', '', $str);
$str = array($str);
print_r($str);
/*
Array
(
[0] => [
[1, 'G4622', '2300866', '1111', 'zzzz'],
[2, 'G4622', '2300873', '2222', 'zzzz'],
[13, 'G4626', '2300975', '3333', 'zzzz'],
]
)
//want to get 2300975
Upvotes: 0
Views: 261
Reputation: 1982
There are two approaches for your task:
Below is an example of both approaches:
<?php
function get_value_dummy($str, $row_id, $column_num)
{
$arr = explode("[".$row_id.",", $str, 2);
if(count($arr) < 2)
return null;
$arr = explode("]", $arr[1], 2);
if(count($arr) < 2)
return null;
$arr = explode(",", $arr[0]);
if($column_num >= count($arr))
return null;
return trim($arr[$column_num-1], " '");
}
function get_value_smart($str, $row_id, $column_num)
{
eval("\$arr=".$str.";");
if(is_null($arr) || (is_array($arr) == false))
return null;
foreach($arr as $subarr)
{
if(!is_array($subarr) || empty($subarr))
continue;
if(reset($subarr) == $row_id)
return array_key_exists($column_num, $subarr)?$subarr[$column_num]:null;
}
return null;
}
$searchLine = "13";
$str = "[
[1, u'G4622', u'2300866', u'1111', u'zzzz'],
[2, u'G4622', u'2300873', u'2222', u'zzzz'],
[13, u'G4626', u'2300975', u'3333', u'zzzz'],
]";
$str = str_replace('u', '', $str);
assert(get_value_dummy($str, $searchLine, 2) == "2300975");
assert(get_value_smart($str, $searchLine, 2) == "2300975");
?>
Upvotes: 1