PHP非法字符串偏移量(illegal string offset)警告求助
Hey there, let's break down why you're hitting that illegal string offset warning and how to fix it.
The Root of the Problem
Looking at your code snippet, the issue lies in how you're looping through your $data2 array:
$data2 = array( 'EquipmentName' => $this->input->post('txt_equipb'), 'EquipmentType' => $this->input->post('txt_equiptype'), 'RequirementID' => $id2 ); foreach($data2 as $d) { $data2s = array('EquipmentName' => $d['Equipment... }
When you use foreach($data2 as $d), each $d grabs the value of each key in your associative array—so $d becomes a string (like the input value from txt_equipb), not a sub-array. Trying to access $d['EquipmentName'] then treats that string as an array, which triggers the error.
How to Fix It
You have two common scenarios here, depending on your use case:
Scenario 1: You're working with a single equipment entry
If you only need to create one $data2s entry from $data2, you don't need a loop at all. Just assign the array directly:
$data2 = array( 'EquipmentName' => $this->input->post('txt_equipb'), 'EquipmentType' => $this->input->post('txt_equiptype'), 'RequirementID' => $id2 ); // Assign directly to $data2s $data2s = $data2; // Or wrap it in an array if you need it for a batch operation $data2s = array($data2);
Scenario 2: You're submitting multiple equipment entries
If your form is set up to submit multiple pieces of equipment (e.g., repeated fields with [] in their names like txt_equipb[]), your initial array structure is incorrect. Instead, loop through the submitted arrays:
// Get array values from your form (ensure fields use name="txt_equipb[]") $equipNames = $this->input->post('txt_equipb'); $equipTypes = $this->input->post('txt_equiptype'); $data2s = array(); // Loop through each entry to build your final array foreach($equipNames as $index => $name) { $data2s[] = array( 'EquipmentName' => $name, 'EquipmentType' => $equipTypes[$index], 'RequirementID' => $id2 ); }
Quick Form Check
Double-check your form field names to match your use case:
- For a single entry: Use
name="txt_equipb"(no brackets) - For multiple entries: Use
name="txt_equipb[]"(brackets tell CodeIgniter to return an array instead of a single string)
内容的提问来源于stack exchange,提问作者Cedrix Cedrix

