Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
This is my first time working with json, just playing around with some data.
This is part of my json
Array
(
[DataSet] => Array
(
[Table] => Array
(
[0] => Array
(
[Driver] => John Doe
[Shift Date] => 2018-01-05T00:00:00-05:00
I want to be able to get all the [Driver] and [Shift Date] fields and put them into a table. It has 2 columns Driver and ShiftDate, not sure where I go from here.
After lots of googling I have come up with the solution, and I apologize if I didn't word my question right this is my first crack at this, but I figured posting the answer may help someone else trying to figure this out:
$str = file_get_contents('./cgapi.json');
$json = json_decode($str, true);
foreach($json['DataSet']['Table'] as $item) {
$stmt = $dbcon->prepare("INSERT INTO DriverData (DriverName, ShiftDate, Minutes, Stops, Gallons) VALUES (?,?,?,?,?)");
$stmt->bind_param("sssss", $item['Driver'], $item['Shift Date'], $item['Minutes'], $item['Stops'], $item['Gallons']);
$stmt->execute();
$stmt->close();
}
$drivers = array_column('Driver', $yourData);
$dates = array_column('Shift Date', $yourData);
Array column extracts all the values of the key provided as the first argument.
http://php.net/manual/en/function.array-column.php
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I’m having issues with an array in PHP. I create an array, it’s good, but in order to see it I use json_encode. See examples below.
Original array:
Array (
[0] => Array ( [0] => GCXO )
[1] => Array ( [0] => LEAS )
[2] => Array ( [0] => LECO )
)
I get this:
[["GCXO"],["LEAS"],["LECO"]]
I want this:
["GCXO", "LEAS", "LECO"]
The problem is that if I don’t use json_encode it returns the word array.
Does anyone knows how to get that result?
If the JSON shows [["GCXO"],["LEAS"],["LECO"]] then you have a multi-dimensional array and need to flatten it to get ["GCXO", "LEAS", "LECO"]:
echo json_encode(array_merge(...$array));
When you use json_encode, you are in fact converting the array to a JSON object, its not longer an "array".
If you only want to see the content of the array, you can use:
print_r($array)
or, you can format it as you like with a loop accessing it values with $array[iterator]
Also you can iterate trough it with foreach, giving it the format that you need.
foreach($array as $object){
echo ','.$object;
}
for example
use function implode(',', $array);
https://www.php.net/manual/en/function.implode.php
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Below is my array I have to convert first value as key and second as value,
Array
(
[0] => Array
(
[region_code] => AB
[region_name] => Alberta
)
)
Please suggest best solutions.I am using array map but its not working.
You can use array_column(), demo
[(PHP 5 >= 5.5.0, PHP 7)] refer to Call to undefined function array_column()
array_column($array, 'region_name', 'region_code');
for older version of php
foreach ($array as $v) {
$result[$v['region_code']] = $v['region_name'];
}
try it out.
$arr = Array(0 => Array('region_code' => 'AB','region_name' => 'Alberta'));
print_r(array_column($arr, 'region_name', 'region_code'));
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a MySQL database with a 'params' field containing Json encoded data. An example of the field contents is:
{"subcustom":{"slaveusers":["Jon Doe"]}}
How can I extract the name "Jon Doe" using Php?
Use json_decode to transform your json string into an object, if you know what you are looking for, do
<?php
$json = '{"subcustom":{"slaveusers":["Jon Doe"]}} ';
$obj = json_decode($json);
print_r($obj->subcustom->slaveusers[0]) ; // Jon Doe
?>
if you don't know the structure of your json, use a print_r or vardump to check the content
To do this as array you add the 'true' flag to json_decode():
$json = '{"subcustom":{"slaveusers":["Jon Doe"]}} ';
$json_array = json_decode($json, true);
print_r($json_array); // Array ([subcustom] => Array ([slaveusers] => Array ([0] => Jon Doe)))
Once you have an array you can follow the tree to get the element(s) you want:
echo $json_array['subcustom']['slaveusers'][0]; // Jon Doe
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
My variable which retrieve from database is:
$MyVariable="1=>'raju',2=>'rana',3=>'keya',4=>'muaz',5=>'',6=>'Asif'";
My array will be:
$MyArray=array($MyVariable);
Now I want to print a value using a key. Like:
echo $MyArray[2];
My output should be:
rana
But output is nothing!
eval() has security implications, but that's how this string of partial crap is turned into an actual array:
eval('$MyArray = array('.$MyVariable.');');
print_r($MyArray);
You should really store each value as a related row in another table instead of array data.
Your variable $myVariable is a string consisting of array keys.
If you were to write it as an array, it would work without problems:
$myvariable = array(
1 => 'raju',
2 => 'rana',
3 => 'keya'
// More entries
);
If this is the output of a function, you may want to make that function output JSON instead, as that is parseable to an array with just one json_decode call.
If you still want to parse this, you'll have to do some more advanced string parsing:
$data = array();
$bits = preg_match_callback("/(\d+)=>'(.*?)'(\,)?/", function($matches) use ($data){
$data[$matches[1]] = $matches[2];
}, $MyVariable);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am fetching data from a database as a string like 02-feb-1990 I want to remove all the characters from the string, and have only date of year means 1990.
How can I achieve this in PHP using regex or any other method
This should work for you:
<?php
$input = "02-feb-1990";
echo $year = substr($input, -4);
?>
Output:
1990
If you want to use regex:
<?php
$input = "02-feb-1990";
preg_match_all("/\d{4}$/", $input, $matches);
print_r($matches);
?>
Output:
Array ( [0] => Array ( [0] => 1990 ) )
In order to retrieve a 4 digit year from dd-mmm-yyyy using regex, you can use the following:
$date = "02-feb-1990"
preg_match('/\d{4}/', $date, $year);
echo $year[0];
The above will match the first 4 digit number you come across, which in this instance, will always be the 4-digit year.