How to implode and foreach get - php

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...

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;

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

PHP separate number based on 2 delimiter

PHP seperate number using based on 2 delimiter
I have this variable $sid
$sid = isset($_POST['sid']) ? $_POST['sid'] : '';
and it's output is:
Array
(
[0] => 4|1
[1] => 5|2,3
)
Now I want to get the 1, 2, 3 as value so that I can run a query based on this number as ID.
How can I do this?
Use explode()
$arr = array(
0 => "4|1",
1=> "5|2,3"
);
$output = array();
foreach($arr as $a){
$right = explode("|",$a);
$rightPart = explode(",",$right[1]);
foreach($rightPart as $rp){
array_push($output,$rp);
}
}
var_dump($output);
Use foreach to loop thru your array. You can explode each string to convert it to an array. Use only the 2nd element of the array to merge
$sid = array('4|1','5|2,3');
$result = array();
foreach( $sid as $val ) {
$val = explode('|', $val, 2);
$result = array_merge( $result, explode(',', $val[1]) );
}
echo "<pre>";
print_r( $result );
echo "</pre>";
You can also use array_reduce
$sid = array('4|1','5|2,3');
$result = array_reduce($sid, function($c, $v){
$v = explode('|', $v, 2);
return array_merge($c, explode(',', $v[1]));
}, array());
These will result to:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
You can do 2 explode with loop to accomplish it.
foreach($sid as $a){
$data = explode("|", $a)[1];
foreach(explode(",", $data) as $your_id){
//do you stuff with your id, for example
echo $your_id . '<br/>';
}
}

split string into array object in php

I have a string like this: "abc#gmail.com;ABC,xyz#gmail.com;XYZ" and I want to convert into array boject. How can I do that?
Below is sample
$noactivity_noassignedto = "abc#gmail.com;ABC,xyz#gmail.com;XYZ";
$assignedto = explode(';', $noactivity_noassignedto);
$assignedto = array((object) array("Email" => $assignedto[0], "Name" => $assignedto[1]));
$fromadd = 'some#abc.com';
$fromname = 'somename';
/*sending mail here*/
$this->init()->setsubject($sub)->addto($assignedto)->setfrom($fromadd, $fromname)->send();
Try this code:
$noactivity_noassignedto = "abc#gmail.com;ABC,xyz#gmail.com;XYZ";
$assignedto = explode(',', $noactivity_noassignedto);
foreach ($assignedto as $recipient) {
$tmp = explode(';', $recipient);
$recipients[] = (object)array("Email" => $tmp[0], "Name" => $tmp[1]);
}
$recipients = (object)$recipients;
$noactivity_noassignedto = "abc#gmail.com;ABC,xyz#gmail.com;XYZ";
$elements = explode(',', $noactivity_noassignedto);
foreach ($elements as $element) {
$dummy = explode(';', $element);
$assignedto[] = (object)array("Email" => $dummy[0], "Name" => $dummy[1]);
}
You need two explode
$noactivity_noassignedto = "abc#gmail.com;ABC,xyz#gmail.com;XYZ";
$assignedAll = explode(',', $noactivity_noassignedto);
// here you can put loop to send all, for now just first
$assignedto = explode(';', $assignedAll[0]);
$assignedto = array((object) array("Email" => $assignedto[0], "Name" => $assignedto[1]));
This will generate the array of objects that you want
$noactivity_noassignedto = "abc#gmail.com;ABC,xyz#gmail.com;XYZ";
$assignedto = explode(',', $noactivity_noassignedto);
foreach($assignedto as $item) {
list($email, $name) = explode(';', $item);
$addresses[] = (object)['Name'=>$name, 'Email'=>$email];
}
print_r($addresses);
Result: a print_r($addresses);
Array
(
[0] => stdClass Object
(
[Name] => ABC
[Email] => abc#gmail.com
)
[1] => stdClass Object
(
[Name] => XYZ
[Email] => xyz#gmail.com
)
)
You are on the right path. explode is what you are looking for to split a string into an array.
Given
$str = "abc#gmail.com;ABC";
$arr = explode($str, ';');
$arr will be array('abc#gmail.com', 'ABC');.
I think your problem is you want to invoke this multiple times. To do this:
$str = "abc#gmail.com;ABC,def#gmail.com;DEF";
$people = explode($str, ',');
foreach ($people as $person) {
$assigned_to = explode($person, ';');
// rest of your code
}

applying array_unique

I have code to get the address which is separated by space and then fetching area details about that address so each time sql result is stored in array "resultArray" and that result is pushed to another array "returnArray" which is then displayed in the format of json.I want to remove duplicate area_id in returnArray so I used "array_unique" but it's not working .Please give some suggestion.
Sample Code:
<?php
include_once 'main.php';
$dac = new Main();
$add = $_POST['address'];
$noLines = sizeof($add);
$resultArray=array();
$returnArray=array();
$returnArrayMain=array();
while ($noLines>0)
{
$resultArray=array();
$result = $dac->area_detail($add[$noLines-1]);
$count=mysql_num_rows($result);
while($row = mysql_fetch_assoc($result))
{
$resultArray[]=array('area_id' => $row['area_id'],'area_name' => $row['area_name'],'area_GISlat'=>$row['area_GISlat'],'area_GISlon'=>$row['area_GISlon']);
}
array_push($returnArray, $resultArray) ;
$noLines = $noLines-1;
}
$returnArrayMain = array_unique($returnArray);
echo json_encode($returnArrayMain);
?>
Here is solution with a testing associative array:
// this is testing array as you are using:
$resultArray = array(
array(
'area_id' => 12,
'area_name' => 'test',
'area_GISlat'=>'test2',
'area_GISlon'=>'test3'),
array(
'area_id' => 11,
'area_name' => 'test',
'area_GISlat'=>'test2',
'area_GISlon'=>'test3'),
array(
'area_id' => 12,
'area_name' => 'test',
'area_GISlat'=>'test2',
'area_GISlon'=>'test3')
);
// take a temporary arry
$temporaryArr = array();
// initialize key's array
$arrayKey = array();
foreach ( $resultArray as $key => $values ) {
if ( !in_array($values, $temporaryArr) ) {
$temporaryArr[] = $values; // store values in temporary array
$arrayKey[$key] = true; // store all keys in another array
}
}
// now use array_intersect_key function for intersect both array.
$requiredArr = array_intersect_key($resultArray, $arrayKey);
echo "<pre>";
print_r($requiredArr);
Result:
Array
(
[0] => Array
(
[area_id] => 12
[area_name] => test
[area_GISlat] => test2
[area_GISlon] => test3
)
[1] => Array
(
[area_id] => 11
[area_name] => test
[area_GISlat] => test2
[area_GISlon] => test3
)
)
Removed duplicate arrays.
From PHP Manual:
array_intersect_key — Computes the intersection of arrays using keys for comparison
Side note:
Also add error reporting to the top of your file(s) right after your opening <?php tag
error_reporting(E_ALL);
ini_set('display_errors', 1);
try this
$returnArrayMain = array_map("unserialize", array_unique(array_map("serialize", $resultArray)));
try this..
$returnArrayMain = uniqueAssocArray($returnArray, 'area_id');
echo json_encode($returnArrayMain);
function uniqueAssocArray($array, $uniqueKey) {
if (!is_array($array)) {
return array();
}
$uniqueKeys = array();
foreach ($array as $key => $item) {
$groupBy=$item[$uniqueKey];
if (isset( $uniqueKeys[$groupBy]))
{
//compare $item with $uniqueKeys[$groupBy] and decide if you
//want to use the new item
$replace= ...
}
else
{
$replace=true;
}
if ($replace) $uniqueKeys[$groupBy] = $item;
}
return $uniqueKeys;
}

Help with Array List - PHP MYSQL

I have an array value like this.
My print_r($_POST) looks like this.
I can get the post count value too. (Here the count value is 3)
Array ( [tag] => Array ( [4-a] => User1 [8-a] => User2 [3-a] => User3 ))
Now, i want the above array values in a single string.
For ex:
$all_users = User1,User2,User3
Is this possible . Pl advice.
Haan
$all_users = implode(',',$your_array);
If i understand your question well...
$array = Array ( 'tag' => Array ( '4-a' => 'User1', '8-a' => 'User2', '3-a' => 'User3' ));
$allUsers = '';
$first = true;
foreach($array['tag'] as $key=>$value) {
if($first == false) {
$allUsers .= ',' . $value;
} else {
$allUsers .= $value;
}
$first = false;
}
echo $allUsers;

Sort an associative array in php with multiple condition

Consider following array
$details = array(
array('lname'=>'A', 'fname'=>'P','membkey'=>700,'head'=>'y'),
array('lname'=>'B', 'fname'=>'Q','membkey'=>540,'head'=>'n'),
array('lname'=>'C', 'fname'=>'R','membkey'=>700,'head'=>'n'),
array('lname'=>'D', 'fname'=>'S','membkey'=>540,'head'=>'y'),
array('lname'=>'E', 'fname'=>'T','membkey'=>700,'head'=>'n')
);
Here I would like to sort with head and membkey. Top element of same membkey element should have 'head=y' and echoed as,
$details = array(
array('lname'=>'A', 'fname'=>'P','membkey'=>700,'head'=>'y'),
array('lname'=>'E', 'fname'=>'T','membkey'=>700,'head'=>'n'),
array('lname'=>'C', 'fname'=>'R','membkey'=>700,'head'=>'n'),
array('lname'=>'D', 'fname'=>'S','membkey'=>540,'head'=>'y'),
array('lname'=>'B', 'fname'=>'Q','membkey'=>540,'head'=>'n')
);
I tried it as follows
function orderbymemberKey( $a, $b ){
if ( $a[membkey] == $b[membkey] )
return 0;
return($a[membkey] < $b[membkey] )? -1 :1;
}
usort( $details, orderbymemberKey );
and it successfully order by membkey.
Any suggestions please.
You're half way there (though you were sorting backwards for membkey based on your example):
function order_by_member_key($a, $b)
{
if ($a['membkey'] == $b['membkey'])
{
// membkey is the same, sort by head
if ($a['head'] == $b['head']) return 0;
return $a['head'] == 'y' ? -1 : 1;
}
// sort the higher membkey first:
return $a['membkey'] < $b['membkey'] ? 1 : -1;
}
usort($details, "order_by_member_key");
Is this array being pulled from a database? Because, if so, you should be able to make use of ORDER BY clauses to clean it up outside of php.
<?php
$membkey = array();
$head = array();
foreach ($details as $key => $row) {
$membkey[$key] = $row['membkey'];
$head[$key] = $row['head'];
}
array_multisort($membkey, SORT_DESC, $head, SORT_DESC, $details);
print_r($details);
Or, an even more generic solution:
function sort_by($array) {
$arguments = func_get_args();
$array = array_pop($arguments);
$variables = array();
foreach ($arguments as $index => $key) {
$variables[] = '$arguments['.$index.']';
if ($index % 2 == 0) {
$arguments[$index] = array();
foreach ($array as $row) $arguments[$index][] = $row[$key];
}
}
// call_user_func_array will not work in this case
eval('array_multisort('.implode(', ', $variables).', $array);');
return $array;
}
print_r(sort_by('membkey', SORT_DESC, 'head', SORT_DESC, $details));
Ugly but someone wrote a function on php.net:
http://php.net/manual/en/function.sort.php
<?php
$array[0]['name'] = 'Chris';
$array[0]['phone'] = '3971095';
$array[0]['year'] = '1978';
$array[0]['address'] = 'Street 1';
$array[1]['name'] = 'Breanne';
$array[1]['phone'] = '3766350';
$array[1]['year'] = '1990';
$array[1]['address'] = 'Street 2';
$array[2]['name'] = 'Dusty';
$array[2]['phone'] = '1541120';
$array[2]['year'] = '1982';
$array[2]['address'] = 'Street 3';
function multisort($array, $sort_by, $key1, $key2=NULL, $key3=NULL, $key4=NULL, $key5=NULL, $key6=NULL){
// sort by ?
foreach ($array as $pos => $val)
$tmp_array[$pos] = $val[$sort_by];
asort($tmp_array);
// display however you want
foreach ($tmp_array as $pos => $val){
$return_array[$pos][$sort_by] = $array[$pos][$sort_by];
$return_array[$pos][$key1] = $array[$pos][$key1];
if (isset($key2)){
$return_array[$pos][$key2] = $array[$pos][$key2];
}
if (isset($key3)){
$return_array[$pos][$key3] = $array[$pos][$key3];
}
if (isset($key4)){
$return_array[$pos][$key4] = $array[$pos][$key4];
}
if (isset($key5)){
$return_array[$pos][$key5] = $array[$pos][$key5];
}
if (isset($key6)){
$return_array[$pos][$key6] = $array[$pos][$key6];
}
}
return $return_array;
}
//usage (only enter the keys you want sorted):
$sorted = multisort($array,'year','name','phone','address');
print_r($sorted);
//output:
Array ( [0] => Array ( [year] => 1978 [name] => Chris [phone] => 3971095 [address] => Street 1 ) [2] => Array ( [year] => 1982 [name] => Dusty [phone] => 1541120 [address] => Street 3 ) [1] => Array ( [year] => 1990 [name] => Breanne [phone] => 3766350 [address] => Street 2 ) )

Categories