This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 1 year ago.
I have a DB column with a string as shown below
{"gpslev":"11","gsmlev":"4","hdop":"0.4","io16":"202847595","io175":"-1","io200":"0","io236":"0","io239":"0","io240":"0","io241":"65510","io247":"0","io251":"0","io252":"0","io253":"0","io254":"25","io310":"0","io66":"12299","io67":"4014","io68":"0","io69":"1","pdop":"0.5"}
I want to extract certain data from this string and echo it to a PHP page
I have used the following to no avail
function populateArrayFromString($string)
{
$array = [];
$pairs = explode(",", $string);
foreach ($pairs as $pair) {
list($key, $value) = explode(":", $pair);
$arrayToReturn[trim($key, '"')] = trim($value, '"');
}
return $array;
}
$result = mysql_query("SELECT * FROM gs_objects WHERE imei = '354018115539821' ");
?>
<?php
while ($row = mysql_fetch_array($result)) {
$data = populateArrayFromString($row['params']);
?>
<?php echo $row['params']; ?>
</br>
<?php echo $data['io16']; ?>
If I echo the PARAMS coumn I see the whole string. If I echo the io16 in the param colum I get error
Notice: Undefined index: io16
use
$stmt = '{"gpslev":"11","gsmlev":"4","hdop":"0.4","io16":"202847595","io175":"-1","io200":"0","io236":"0","io239":"0","io240":"0","io241":"65510","io247":"0","io251":"0","io252":"0","io253":"0","io254":"25","io310":"0","io66":"12299","io67":"4014","io68":"0","io69":"1","pdop":"0.5"}';
$result = json_decode($stmt,true);
print_r($result);
and you will get and array
Array
(
[gpslev] => 11
[gsmlev] => 4
[hdop] => 0.4
[io16] => 202847595
[io175] => -1
[io200] => 0
[io236] => 0
[io239] => 0
[io240] => 0
[io241] => 65510
[io247] => 0
[io251] => 0
[io252] => 0
[io253] => 0
[io254] => 25
[io310] => 0
[io66] => 12299
[io67] => 4014
[io68] => 0
[io69] => 1
[pdop] => 0.5
)
No nbeed to self poarse the json
Related
I have a multidimensional array which has keys and key has values or have another array with keys and values so I want to search by keys but in input like 230 is user input
and it will go to 3 then 4 then 1 if result is a value but not an array it must print the value like
input = 230 result should be = "3-4-1"
so I need to str_split the number and search it 1 by 1 if first number is array then look for second kinda
edit1 = I found the way to split the key
//edit1
$keys = "021";
$keysSplit =str_split($keys, strlen($keys)/strlen($keys));
echo $keys[0];
//edit 1 ends
$arr = [0 => [0=>"1-1", 1 => "1-2" , 2=>"1-3", 3=>[0=>"1-4-1", 1 => "1-4-2" , 2=>"1-4-3"]],
1 => [0=>"2-1", 1 => "2-2" , 2=>"2-3"],
2 => [0=>"3-1", 1 => "3-2" , 2=>"3-3", 3=>[0 =>"3-4-1" , 1=> "3-4-2"]],
];
$keys = "021";
function searchByKey($array , $keys){
$result = [];
$keys = "021";
$keys =str_split($keys, strlen($keys)/strlen($keys));
$key1 = $keys[0];
$key2 = $keys [1];
$key3 = $keys [2];
foreach ($array as $key1 => $value){
if (is_array($value)){
$key1 = null;
$key1 = $key2;
$key2 = $key3;
return searchByKey($value , $key1);
}
else {
$result=$value;
echo $result;
}
}
}
$arr = searchByKey($arr, $keys);
The function only works as key and value given and it will print every key and value on the key it asked first so its not the thing I wanted to do could anyone help and explain?
Answer given by #Anggara I made it in to function ;
$input = "11";
function searchByNumber($array, $input){
$result = $array;
for ($i = 0; $i < strlen($input); $i++) {
if (is_array($result)) {
$result = $result[$input[$i]];
} else {
$result = "Does not exists";
break;
}
}
echo $result;
}
$arr = searchByNumber($arr, $input);
You can access char in string like accessing an array. For example:
$input = "230";
// $input[0] is "2"
// $input[1] is "3"
// $input[2] is "0"
So my approach is to loop for each character in input key, and look for corresponding value in $arr. Each iteration will set found array element into variable $result. If the searched key does not exist (ex: "021"), print error message.
<?php
$arr = [
0 => [
0 => "1-1",
1 => "1-2",
2 => "1-3",
3 => [
0 => "1-4-1",
1 => "1-4-2",
2 => "1-4-3"
]
],
1 => [
0 => "2-1",
1 => "2-2",
2 => "2-3"
],
2 => [
0 => "3-1",
1 => "3-2",
2 => "3-3",
3 => [
0 => "3-4-1",
1 => "3-4-2"
]
],
];
$input = "230";
$result = $arr;
for ($i = 0; $i < strlen($input); $i++) {
if (is_array($result)) {
$result = $result[$input[$i]];
} else {
$result = 'Can not traverse path';
break;
}
}
echo $result;
After splitting the keys
for($i=0;$i<strlen($keys);$i++){
$arr = $arr[$keys[$i]];
}
if(is_array($arr)){
echo json_encode($arr);
}else{
echo $arr;
}
You need a loop, which will go through the keys one by one and assigning into the array.
i have a loop where i am getting items from database, currently there are 314 ids in my array and i get the items like so.
$s_standards = [];
$s_sub_category = [];
foreach ($sanitized_needs['standard'] as $skey => $standard) {
$sname = DB::table('lesson_observation_teacher_standards')->where('id', $standard)->first()->name;
$s_standards[] = $sname;
foreach ($sanitized_needs['sub_category'] as $key => $substandard) {
$name = DB::table('lesson_observation_teacher_standard_categories')->where('id', $substandard)->first()->name;
if ($key == $skey) {
$s_sub_category[$sname][] = $name;
}
}
}
I know i could use WhereIn but i need the duplicates to calculate the categories.
Both $santized_needs['standard'] and $santized_needs['sub_category'] have 314 ids. But when this runs it throws 500 internal server error but when i comment the queries out and replace them with string it works. My guess is the database is restricting mass queries. There's no error message in both laravel.log and network tab in browser.
Is there any way i can disable the restrictions put on database or laravel?
UPDATE: Here are some samples of $sanitized_needs array.
array:2 [
"standard" => array:312 [
0 => "C216114B-8751-3874-9154-FC22679569E0"
1 => "871E5F62-0E1B-3338-969C-2DC4604C8722"
2 => "B0161059-E9F6-376E-8BB1-B4BF1B10C30F"
3 => "D1380FB6-37A8-3B3B-B877-A5AF21D9385F"
4 => "D1380FB6-37A8-3B3B-B877-A5AF21D9385F"
5 => "676038A6-13D0-32CC-BAD7-A7DA9CFB28EA"
6 => "D1380FB6-37A8-3B3B-B877-A5AF21D9385F"
7 => "C216114B-8751-3874-9154-FC22679569E0"
8 => "676038A6-13D0-32CC-BAD7-A7DA9CFB28EA"
9 => "676038A6-13D0-32CC-BAD7-A7DA9CFB28EA"
10 => "C216114B-8751-3874-9154-FC22679569E0"
...
]
"sub_category" => array:312 [
0 => "B2A688A3-1C72-31F4-91CD-6891B5A1D512"
1 => "5E896BF5-2A99-3059-900A-E1BBBDABF20D"
2 => "050582A4-003B-3034-A401-040D51A8A751"
3 => "63ACE688-9F88-3C63-9556-2A291A9C7651"
4 => "4B8D400E-8160-3D1C-A846-33BA8E93AFB3"
5 => "7AEE6E97-2F84-3EAA-BC8D-409C6DD48CA3"
6 => "4B8D400E-8160-3D1C-A846-33BA8E93AFB3"
7 => "5A878A27-85FC-3FC5-B8FA-70AB7A35D1EB"
8 => "7AEE6E97-2F84-3EAA-BC8D-409C6DD48CA3"
9 => "7AEE6E97-2F84-3EAA-BC8D-409C6DD48CA3"
10 => "596547E6-F3CD-3732-913B-68862898F16C"
...
]
]
Tried everything i could ended up changing this part of the code like so
$s_standards = [];
$s_sub_category = [];
$all_subs = DB::table('lesson_observation_teacher_standard_categories')->pluck('name','id')->toArray();
foreach ($sanitized_needs['standard'] as $skey => $standard) {
$sname = DB::table('lesson_observation_teacher_standards')->where('id', $standard)->first()->name;
$s_standards[] = $sname;
foreach ($sanitized_needs['sub_category'] as $key => $substandard) {
$name = $all_subs[$substandard];
if ($key == $skey) {
$s_sub_category[$sname][] = $name;
}
}
}
Now i am just preloading the categories and searching them in array.
Now it works fine
This question already has answers here:
Create flat array of individual values from rows of comma-separated values fetched from a database table
(5 answers)
Closed 6 months ago.
I know that there are a lot of similar threads on Stack Overflow, but none of them works in my case.
My goal is to get the unique show genres from the database. They are stored (1,2,3 or more) comma separated in the show_genres column.
$link = mysqli_connect('127.0.0.1', 'root', 'pw', 'db');
$query = "SELECT show_genres FROM tv_shows";
$result = mysqli_query($link, $query);
foreach ($result as $value) {
$sh_genres = $value['show_genres'];
$sh_genres_array = array_map('trim', explode(',',$sh_genres));
// $doesnt_work = call_user_func_array("array_merge",
$sh_genres_array); // doesn't work for me
echo '<pre>' . var_export($sh_genres_array, true) . '</pre>';
}
My result is as follows:
array (
0 => 'Drama',
1 => 'Action',
2 => 'Crime',
)
array (
0 => 'Drama',
1 => 'Crime',
)
array (
0 => 'Drama',
1 => 'Thriller',
)
array (
0 => 'DIY',
)
array (
0 => 'Drama',
1 => 'Mystery',
2 => 'Supernatural',
)
However, I need just one array which contains the unique values, such as:
array (
0 => 'Drama',
1 => 'Mystery',
2 => 'Supernatural',
4 => 'Thriller',
5 => 'DIY',
6 => 'Crime',
7 => 'etc...'
)
If I try to create some array before the foreach loop and then store the data into it, such approach doesn't give a result as well.
Perhaps, there is a more simple solution by the means of SQL!?!?
Please try this code
In SQL
$query = "SELECT show_genres FROM tv_shows GROUP BY show_genres";
In PHP
$newArray = array();
foreach ($result as $value) {
$sh_genres = $value['show_genres'];
$sh_genres_array = array_map('trim', explode(',',$sh_genres));
$newArray = array_merge($newArray , $sh_genres_array );
}
$newUniqueArray = array_unique($newArray);
try using this code
$link = mysqli_connect('127.0.0.1', 'root', 'pw', 'db');
$query = "SELECT show_genres FROM tv_shows";
$result = mysqli_query($link, $query);
$sh_genres_array = [];
foreach ($result as $value) {
$sh_genres = $value['show_genres'];
$sh_genres_array = array_merge(
$sh_genres_array ,
array_map('trim', explode(',',$sh_genres))
);
}
echo '<pre>' . var_export(array_unique($sh_genres_array), true) . '</pre>';
Update
Please consider normalizing your database
Not sure but try this.
$genre_arr = RecursiveIteratorIterator(new RecursiveArrayIterator($sh_genres_array));
$unique_genre = array_unique($genre_arr);
I have array like this
$non_unique_zip
[0]->[0]91390
[1]ca
[2]1
[1]->[0]91391
[1]ca
[2]1
[2]->[0]91392
[1]ca
[2]1
[3]->[0]91390
[1]ca
[2]2
[4]->[0]91394
[1]ca
[2]2
so basically array has elements where arra[n][0] is zipcode and array[n][2] is buyer_id.
now out of this, i just want the zipcodes which have multiple buyers. so the only thing I want to extract is
[0]->[0]91390
[1]ca
since 91390 is the only zipcode which has buyer as 1 and 2.
I tried
$result = array();
$first = $non_unique_zip[0];
for($i=0; $i<count($non_unique_zip); $i++){
$result = array_intersect ($first, $non_unique_zip[$i]);
$first = $result;
}
but it just gives error undefined offset.
Any help will be appreciated.
If you call $records your starting array, here is a way to get the zips with 3 lines of code:
//array whose keys are zips, and values are # of occurances
$zips = array_count_values(array_column($records,0));
//filter keeps only zips which occur more than once.
$zips = array_filter($zips,function($n){return $n>1;});
//if you only need the zips, you're done! they are the keys
$zips = array_keys($zips);
Live demo
Use an array that keeps track of the zip codes that have already been encountered before. Then when you get a zip that's in that array, you know it's a duplicate.
$zips = array();
$result = array();
foreach ($non_unique_zip as $e) {
$code = $e[0];
if (isset($zips[$code])) { // duplicate, so add to $result
$result[$code] = array($code, $e[1]);
} else {
$zips[$code] = true; // first time, add it to $zips
}
}
Use array_walk like so:
<?php
$non_unique_zip = [
[91390, "ca"],
[91391, "ca"],
[91392, "ca"],
[91390, "ca"],
[91394, "ca"],
];
$unique_zip = [];
$duplicates = [];
array_walk($non_unique_zip, function($data) use(&$unique_zip, &$duplicates){
if(!in_array($data, $unique_zip)){
$unique_zip[] = $data;
}else{
$duplicates[] = $data;
}
});
var_dump( $duplicates );
// PRODUCES::
array (size=1)
0 =>
array (size=2)
0 => int 91390
1 => string 'ca' (length=2)
var_dump( $unique_zip );
// PRODUCES::
array (size=4)
0 =>
array (size=2)
0 => int 91390
1 => string 'ca' (length=2)
1 =>
array (size=2)
0 => int 91391
1 => string 'ca' (length=2)
2 =>
array (size=2)
0 => int 91392
1 => string 'ca' (length=2)
3 =>
array (size=2)
0 => int 91394
1 => string 'ca' (length=2)
I need help working with arrays. I have an array of data from a MySQL query. After printing it in a for loop, I get the following array_flip:
Array (
[Duru 60] => 0
[Maxwell 50] => 1
[Fashanu 70] => 2
[Nwankwo 80] => 3
[Obi 0] => 4
)
The array value is a combination of 2 fields name and total score. What I want to achieve is an array like so:
Array (
[Duru 60] => 60
[Maxwell 50] => 50
[Fashanu 70] => 70
[Nwankwo 80] => 80
[Obi 0] => 0
)
What I want to achieve is to change the default array numeric keys (0,1,2,3,4) to total score obtained from the query.
Here is the code that gave the first array block:
PHP code begins
$dataA = array();
foreach($data as $key => $val){
$dataC = $val['lastname']." ".$val['total'];
array_push($dataA,($dataC));
}
$dataD = (array_flip($dataA));
print_r($dataD);
$dataA = array();
foreach($data as $key => $val){
$dataK = $val['lastname']." ".$val['total'];
$dataV = $val['total'];
$dataA[$dataK] = $dataV;
}
print_r($dataA);
Try this:
$dataA = array();
foreach($data as $key => $val){
$dataC = $val['lastname']." ".$val['total'];
$dataA[$dataC] = $val['total'];
}
print_r($dataA);
Why can't you just do:
$newData = array();
foreach($data as $key => $val) {
$newData[$val['lastname'] . ' ' . $val['total']] = $val['total'];
}
print_r($newData);