Welcome Guest, Not a member yet? Register   Sign In
Problem with array to string
#1

[eluser]bondjp[/eluser]
Hi, i need to get the index values of an array to a string with quotes.
Like this array('1'=>'audi', '2'=>'bmw') to this '1','2'.

With print_r i get '1','2' but doing my query i get an error an this is displayed '\'1\',\'2\''

What i'm doing wrong?

Here's the code:

Controller:
Code:
$code=implode("','", array_keys($code));
$brandcode = "'$code'";

Model:

Code:
$this->db->where('brand.code IN', $brandcode);
#2

[eluser]bondjp[/eluser]
Changed the code to this but still getting the error in query...

Code:
$brandcode="'" . implode("','", array_keys($code)) . "'";
#3

[eluser]Federico Baña[/eluser]
You're creating an associative array instead of one with a numeric index, that's why you dont get the result you want from implode(), I think.

Try it like this:
$arr = array( 'asd1', 'asd2', 'asd3' );

Then:
print_r( $arr[0] ) => 'asd1'
print_r( $arr[1] ) => 'asd2'
print_r( $arr[2] ) => 'asd3'

Hope this helps.
#4

[eluser]bondjp[/eluser]
[quote author="Federico Bana" date="1280381064"]You're creating an associative array instead of one with a numeric index, that's why you dont get the result you want from implode(), I think.

Try it like this:
$arr = array( 'asd1', 'asd2', 'asd3' );

Then:
print_r( $arr[0] ) => 'asd1'
print_r( $arr[1] ) => 'asd2'
print_r( $arr[2] ) => 'asd3'

Hope this helps.[/quote]


The array that i got is like this: '5345'=>'value1','5235'=>'value2','76542'=>'value3'.

I just want the indexes '5345','5235','76542' so that i can do the query
Code:
WHERE( 'brandcode IN', $brancode);

From what i saw i need to get the values in quotes so that the query would work...
#5

[eluser]Federico Baña[/eluser]
then:

Code:
$arr = array(
    '1234' => 'value1',
    '3456' => 'value2'
);
$keys = array_keys( $arr );

Code:
WHERE( 'brandcode IN', implode( ',', $keys )
#6

[eluser]bondjp[/eluser]
[quote author="Federico Bana" date="1280381781"]then:

Code:
$arr = array(
    '1234' => 'value1',
    '3456' => 'value2'
);
$keys = array_keys( $arr );

Code:
WHERE( 'brandcode IN', implode( ',', $keys )
[/quote]


Thanks. It worked, together with where_in
#7

[eluser]Phil Sturgeon[/eluser]
Why not use $this->db->where_in('brandcode', array_keys( $arr ));?
#8

[eluser]bondjp[/eluser]
[quote author="Phil Sturgeon" date="1280410052"]Why not use $this->db->where_in('brandcode', array_keys( $arr ));?[/quote]

And i don't have to use implode()?
#9

[eluser]Phil Sturgeon[/eluser]
Nope, where_in accepts an array.
#10

[eluser]bondjp[/eluser]
[quote author="Phil Sturgeon" date="1280416602"]Nope, where_in accepts an array.[/quote]

Thanks Phil, It works great!




Theme © iAndrew 2016 - Forum software by © MyBB