Home > Software engineering >  How to implode and foreach get
How to implode and foreach get

Time:11-16

I try to take each "name" and send it to my database for verification the problem is that I can't take each one and go through the foreach

$name = $this->UserSkills->where('id', session()->get('id'))->first();
print_r($name) // return Array ( 
                          [id] => 5 
                          [user] => 15 
                          [name] => name,name1,name2,name3,name4
                         )

$name = implode(",", $name['name']);

foreach($name as $row) {
    $setname[] = $this->checkName->getIDbyName($row['name']);
}

$setname = implode(",", $setname);

$data['id_name'] = $setname;

finally I want him back

echo $data['id_name'] // return: 1,4,8,367, etc...

CodePudding user response:

Your first usage of implode is incorrect, you need explode to take a string and make it into an array.

<?php

$name = $this->UserSkills->where('id', session()->get('id'))->first();

$name = explode(",", $name['name']);

foreach($name as $row) {
    $setname[] = $this->checkName->getIDbyName($row);
}

$setname = implode(",", $setname);

$data['id_name'] = $setname;

CodePudding user response:

I think your $name['name'] returns string not array, So you need to explode() not to implode().

Try something like this:

$name = $this->UserSkills->where('id', session()->get('id'))->first();
print_r($name); // return Array ([id] => 5, [user] => 15, [name] => name,name1,name2,name3,name4)

$names = explode(',', $name['name']); // return Array (0 => name, 1 => name1, 2 => name2, 3 => name3, 4 => name4)

foreach ($names as $row) {
    $setname[] = $this->checkName->getIDbyName($row['name']);
}

$setname = implode(",", $setname); // return 1,4,8,367, etc
$data['id_name'] = $setname; // return 1,4,8,367, etc

echo $data['id_name']; // return 1,4,8,367, etc

Assuming that your getIDbyName() return ID as integer

  • Related