You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP非法字符串偏移量(illegal string offset)警告求助

Fixing the "Illegal String Offset" Error in Your Code

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:08:49