I am trying to import an Excel file into my table using the MaatWebsite package. But every time I get errors like these:
Illegal string offset 'Emp'
I am following this tutorial. And here is the code I have tried:
$path = $request->file('attendance_data')->getRealPath();
$data = Excel::load($path)->get();
if($data->count() > 0)
{
foreach($data->toArray() as $key => $value)
{
foreach($value as $row)
{
$insert_data[] = array(
'employee_card' => $row['Emp'],
'attendance_date' => $row['Date'],
'attendance_time' => $row['On'],
);
}
}
if(!empty($insert_data))
{
DB::table('attendance_logs')->insert($insert_data);
}
Any help will be appreciated
I can't comment so I've posted this as an answer.
Have you tried to die and dump the $row to check that it is an array of key => value pairs as you're expecting? The error looks to show up when trying to access a key of an array with numeric keys. This could also happen if $row is a string, as you can access string characters using a numeric index similar to an array.
$path = $request->file('attendance_data')->getRealPath();
$data = Excel::load($path)->get();
if($data->count() > 0) {
foreach ($data->toArray() as $key => $value) {
foreach ($value as $row) {
// Print the data of $row to see what it actually is
// and kill the process
dd($row);
$insert_data[] = array(
'employee_card' => $row['Emp'],
'attendance_date' => $row['Date'],
'attendance_time' => $row['On'],
);
}
}
if (!empty($insert_data)) {
DB::table('attendance_logs')->insert($insert_data);
}
}
This answer looks to be related.
Related
I'm using below logic to store data in JSON format in MySQL using PHP.
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$store .= json_encode(array($value[1] => $value[2]));
else
$store .= json_encode(array($value[1] => trim($value[2])));
}
session_start();
$date = new Date();
$modified = $date->getDate();
$query = ' UPDATE pages SET last_updated_user_author_id = "'.$_SESSION['user_id'].'", data = "'.htmlentities($store, ENT_QUOTES).'", modified = "'.$modified.'" WHERE id = "'.$pageID.'" ';
Then while decoding the data i'm using below logic:
$query = ' SELECT data FROM pages WHERE id = "'.$_POST['pageID'].'" ';
$connection = $this->establish_connection();
$data = $connection->query($query);
$connection->close();
if($data->num_rows > 0)
{
while($row = $data->fetch_assoc())
{
$var = html_entity_decode($row['data']);
echo json_decode($var);
}
}
While json_decode it shows no data in response, when i did var_dump it shows null, but if i did not do json_decode and only used html_entity_decode() i get below output
{"page_base_url":"http://www.myblog.com/about/contact/"}{"page_url_revision":"http://www.myblog.com/about/contact/"}{"page_url_alternate":"http://www.myblog.com/about/contact/"}{"page_url_shortlink":"http://www.myblog.com/about/contact/"}{"page_url_canonical":"http://www.myblog.com/about/contact/"}{"page_title":"Example | Contact"}{"page_name":"Example Contact"}{"page_type":"WebSite"}{"page_meta_description":"Want to get in touch with us? You're on the correct page, you can get in touch with us by filling the form below. We will get in touch with you with 24 hours."}{"page_keywords":["example","contact","support","help","getintouch","feedback","bug","updates"]}
I'm not sure where i'm going wrong, could anybody help me out here?
I want to give an eccho in json_encode format as a response to ajax call. i use below logic to do so
echo json_encode(
array(
"type" => "error",
"status" => "Error While Retrieving Data!",
"message" => $error
)
);
I think you need something like:
$store = array();
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$store[] = array($value[1] => $value[2]);
else
$store[] = array($value[1] => trim($value[2]));
}
$save = json_encode($store);
or even (if your $value[1] is always unique within the loop)
$store = array();
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$store[$value[1]] = $value[2];
else
$store[$value[1]] = trim($value[2]);
}
$save = json_encode($store);
then use $save to store in your table. I'm not 100% on that, though.
The string you've shown is not valid JSON. If you wanted to store a list of objects like that in JSON format, they need to be within an array, and separated by commas. Otherwise they are just unrelated individual objects and cannot be decoded as a single block of JSON.
Therefore you need to build an array in PHP and then encode the whole thing at the end. Something like this:
$storedata = array();
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$storedata[] = array($value[1] => $value[2]);
else
$storedata[] = array($value[1] => trim($value[2]));
}
$jsondata = json_encode($storedata);
And then use $jsondata in your SQL statement.
Your problem is your "saving" to the database. You encode every key-value-pair in an own json-string and concat those json-strings.
Your snippet
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$store .= json_encode(array($value[1] => $value[2]));
else
$store .= json_encode(array($value[1] => trim($value[2])));
}
Yields $store = "{key1:value1}{key2:value3}{key3:value3}". Note all the brackets, you have 3 distinct json-objects with a single key-value pair in your string, instead of one json-object with 3 key-value-pairs.
However, I assume you want a single json-object with the key-value-pairs as result like the folling?
$store = "{
key1:value1,
key2:value2,
key3:value3
}";
If so, you need to build your array differently:
$store = array();
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$store[$value[1]] = $value[2];
else
$store[$value[1]] = trim($value[2]);
}
And please, for the safety of everyone, your code is vulnerable of sql-injections. Please fix that, too.
This question already has answers here:
How can I access an array/object?
(6 answers)
Closed 6 years ago.
i am trying to access the value of an array that i have created, but it seems to fail.
I am looping through an array that sends VIA http, and adding the docno and entryno to new array called $ArrID, it can be added to the new array, however when i try to access the ArrID it seem to get nothing from the array itself while i am confident that ArrID contain the items
CODE
$ArrID = [];
foreach ($form_data_body as $key => $value) {
$docno = $value -> doc_no;
$entryno = $value -> entryno;
if($mysqli->query($sql) == 1){
$itemArr = array('docno' => $docno, 'entryno' => $entryno);
$ArrID[] = $itemArr;
}
}
if(count($ArrID)>0){
foreach ($ArrID as $key => $values) {
echo $values -> docno;
}
}
You are mixing with object and array
see http://php.net/manual/en/language.types.array.php
http://php.net/manual/en/language.types.object.php
$ArrID = [];
foreach ($form_data_body as $key => $value) {
$docno = $value['doc_no'];
$entryno = $value['entryno'];
if($mysqli->query($sql) == 1){
$itemArr = array('docno' => $docno, 'entryno' => $entryno);
$ArrID[] = $itemArr;
}
}
if(count($ArrID)>0){
foreach ($ArrID as $key => $values) {
echo $values['docno'];
}
}
How are you sure that your array has the data? Make sure by echoing the size of the array and see if its greater then zero.
Try the code below and check if it works or not. There was a redundant assign and reassign code, actually you were assigning array to a variable, and variable to an array again.
$ArrID = [];
foreach ($form_data_body as $key => $value) {
$docno = $value -> doc_no;
$entryno = $value -> entryno;
if($mysqli->query($sql) == 1) {
$ArrID[] = array('docno' => $docno, 'entryno' => $entryno);
}
}
if(count($ArrID)>0) {
foreach ($ArrID as $key => $values) {
echo $values -> docno;
}
}
I keep getting the error:
PHP Notice: Undefined offset: 1 in /home/mydomain/mydomain.com/admin/model/tool/export_xls.php on line 150
I've looked at the other similar posts but none of those resolutions work on my code. I don't see any numbers related to the array, and I've double checked for missing closing } . I asked the code developer and all he did was get it to stop displaying the error, but it still shows up (several thousand times) in my error log. line 150 is the blank line above the code
"//Get all options values to each option"
Code:
public function get_all_options()
{
$this->load->model('catalog/option');
$all_options = $this->model_catalog_option->getOptions();
$options_final = array();
//Format options
foreach ($all_options as $key => $op) {
$options_final[$op['name'].'_'.$op['type']] = array(
'option_id' => $op['option_id'],
'option_name' => $op['name'],
'option_values' => array()
);
}
//Get all options values to each option
foreach ($options_final as $option_name => $op) {
$option_values = $this->model_catalog_option->getOptionValues($op['option_id']);
//Format option values
$option_values_final = array();
foreach ($option_values as $key => $op) {
$option_values_final[$op['name']] = $op['option_value_id'];
}
$options_final[$option_name]['option_values'] = $option_values_final;
}
return $options_final;
}
This is because you are accessing an array which index is not set . try something like this
//Format options
foreach ($all_options as $key => $op) {
$options_final[$op['name'].'_'.$op['type']]
= array(
'option_id' =>isset($op['option_id']) ?
:$op['option_id']:null,
'option_name' => isset($op['option_name'])
? :$op['option_name']:null,
'option_values' => array()
);
}
I have an array with structure generated like this:
$groups = array();
while ($group = mysql_fetch_array($groups_result)) {
$groups[] = array( 'id' => $group['id'], 'name' => $group['name']);
}
How can I later in the code get the name of the group by its id? For example, I would like a function like:
function get_name_by_id($id, $array);
But I'm looking for some solution which is already implemented in PHP. I know it would be easier to make arrays with array[5] = array('name' => "foo") etc where 5 in this case is id, but in my code there is a lot of arrays already created like i mentioned above and I cannot easily switch it.
$groups = array();
while ($group = mysql_fetch_assoc($groups_result)) {
$groups[$group['id']] = array( 'name' => $group['name']);
}
$name = $groups['beer']['name'];
also please not using fetch_assoc is more efficient than fetch array
function get_name_by_id($id, $data) {
foreach($data as $d) {
if ($d['id'] == $id) {
return $d['name'];
}
}
// return something else, id was not found
}
Here is example how my array should look like:
$library = array(
'book' => array(
array(
'authorFirst' => 'Mark',
'authorLast' => 'Twain',
'title' => 'The Innocents Abroad'
),
array(
'authorFirst' => 'Charles',
'authorLast' => 'Dickens',
'title' => 'Oliver Twist'
)
)
);
When I get results from oracle database:
$row = oci_fetch_array($refcur, OCI_ASSOC+OCI_RETURN_NULLS);
But when I execute my code I only get one row.
For example: <books><book></book><name></name></books>
But I want all rows to be shown in xml.
EDIT:
This is my class for converting array to xml:
public static function toXml($data, $rootNodeName = 'data', &$xml=null)
{
// turn off compatibility mode as simple xml throws a wobbly if you don't.
if (ini_get('zend.ze1_compatibility_mode') == 1)
{
ini_set ('zend.ze1_compatibility_mode', 0);
}
if (is_null($xml))
{
$xml = simplexml_load_string("<".key($data)."/>");
}
// loop through the data passed in.
foreach($data as $key => $value)
{
// if numeric key, assume array of rootNodeName elements
if (is_numeric($key))
{
$key = $rootNodeName;
}
// delete any char not allowed in XML element names
$key = preg_replace('/[^a-z0-9\-\_\.\:]/i', '', $key);
// if there is another array found recrusively call this function
if (is_array($value))
{
// create a new node unless this is an array of elements
$node = ArrayToXML::isAssoc($value) ? $xml->addChild($key) : $xml;
// recrusive call - pass $key as the new rootNodeName
ArrayToXML::toXml($value, $key, $node);
}
else
{
// add single node.
$value = htmlentities($value);
$xml->addChild($key,$value);
}
}
// pass back as string. or simple xml object if you want!
return $xml->asXML();
}
// determine if a variable is an associative array
public static function isAssoc( $array ) {
return (is_array($array) && 0 !== count(array_diff_key($array, array_keys(array_keys($array)))));
}
}
?>
Now with below responde I have tried problem is I get following output: <book>...</book> tags after each row.. then I tried 3 dimensional array now I get: <book><book>...</book></book> on the proper place but I have 2 of them.
This is the line where I have determine which is root on that array and that's why I get this output. But don't know how to change it : $xml = simplexml_load_string("<".key($data)."/>");
Thank you.
oci_fetch_array() will always return a single row, you need to call it until there are no more rows to fetch in order to get all of them:
while ($row = oci_fetch_array($refcur, OCI_ASSOC+OCI_RETURN_NULLS))
{
$library['book'][] = $row;
}