开发者

explode an array and add array keys

开发者 https://www.devze.com 2023-03-10 20:15 出处:网络
I have a string that looks like this, IT, MEDIA, ADVERTISING I am then doing the following code. $criteria = explode(\",\", $string);

I have a string that looks like this,

IT, MEDIA, ADVERTISING

I am then doing the following code.

$criteria = explode(",", $string);

This obviously creates the following when print_r is run over the $criteria.

array([0] => IT, [1] => MEDIA, [2] => 'ADVERTISING')

I using $criteria to match for keywords in a database in codeigniter application, I am wanting to using something 开发者_StackOverflow社区like,

$this->db->like($criteria);

for this to work though I need the $criteria array to look like this,

array([sector] => IT, [sector] => MEDIA, [sector] => 'ADVERTISING')

How can I do this?


PHP can't have multiple values with the same key.


You cannot build an array like this. The keys of the array are identical, so the values will overwrite each other.

Also I think that the method you are looking for is where_in():

$names = array('Frank', 'Todd', 'James');

$this->db->where_in('username', $names);

// Produces: WHERE username IN ('Frank', 'Todd', 'James')


If you're trying to make OR WHERE clauses with an array like this:

$criteria = array(
    0 => 'IT',
    1 => 'MEDIA',
    2 => 'ADVERTISING',
)

You can loop through it and use like() and or_like() methods:

foreach ($criteria as $index => $value) {
    if ($index == 0)
        $this->db->like('sector', $value);
    else
        $this->db->or_like('sector', $value);
}

// Produces WHERE sector LIKE '%IT%' OR sector LIKE '%MEDIA%' OR sector LIKE '%ADVERTISING%';


How about creating your array criteria like this:

$criteria = array('sector'=>explode(",", $string));

OUTPUT

var_dump($criteria);

array(1) {
  ["sector"]=>
  array(3) {
    [0]=>
    string(2) "IT"
    [1]=>
    string(6) " MEDIA"
    [2]=>
    string(12) " ADVERTISING"
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消