0

I'm trying to access the value ('Id') of an array.

This is my code to access the array:

$value[0]['Id']

This is the error: X

Cannot use string offset as an array

The array that I try to access: Y

array(1) { [0]=> array(1) { ["Id"]=> string(2) "42"} }

The surounding code

$query = "select Id from test where Tags = " .  "\"$chosedOption[1]\""; 
    $result = mysql_query($query, $link);
    $value = mysqlArray($result);
    $value_id = null;
    $value_id = $value[0]['Id']; // gives X
    var_dump($value[0]['Id']); 
    var_dump($value); // gives Y


function mysqlArray($result) {
$table_result = array();
$r = 0;
while($row = mysql_fetch_assoc($result)) {
    $arr_row = array();
    $c = 0;
    while ($c < mysql_num_fields($result)) {
        $col = mysql_fetch_field($result, $c);
        $arr_row[$col -> name] = $row[$col -> name];
        $c++;
    }
    $table_result[$r] = $arr_row;
    $r++;
}
return $table_result; }
13
  • 3
    something doesnt seem right in the dump of your array. It is missing a [ close to "id". Can you show the code of how you initialized the array? It would be helpful
    – boug
    May 10, 2011 at 13:36
  • Is that the array declaration or are you just trying to show us the structure of the array?
    – Joseph
    May 10, 2011 at 13:36
  • @Jospeh: i think that is the result of var_dump($value)
    – boug
    May 10, 2011 at 13:39
  • Yes I edited. And indeed it's a var_dump.
    – user746873
    May 10, 2011 at 14:05
  • 1
    Can you post some of the surrounding code? This should be working fine on the basis of the information we have.
    – Dan
    May 10, 2011 at 14:12

2 Answers 2

0

Can it be that $value_id already has a (string) value?

1
  • $value_id is a never used variable. It's the first time that it has a value. To surest a declare $value_id as follow before $value_id = $value[0]['Id']: as empty $value_id = null; .
    – user746873
    May 10, 2011 at 14:27
0

Replace mysqlArray($result); with mysql_fetch_array($result);

2
  • Strange thing is , is that I cannot reproduce this error. Try this ( with $link ) only , do you still have the error ? what for other code is there on that page ? May 10, 2011 at 14:47
  • With mysql_fetch_array(), you would have to access $value['Id'] rather than $value[0]['Id'].
    – binaryLV
    May 11, 2011 at 6:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.