add key pair value in array in foreach loop PHP - php

I want to make an key pair array in foreach loop in php. In my foreach loop i have city name and user name. I want to add all users for same city in array.
Ex [{city=>'pune',users=>("a","b","c","d")},{'city=>nk',users=>("e","b","c","f")}] or any other array format.
foreach ($studsInfo as $value) {
$studId = "".$value['_id'];
$indDetail = $industryM->getAllIndustries($studId);
$indusArray['industry'] = iterator_to_array($indDetail);
$city = $value['city'];
$name = $value['firstname'];
}
How could I add all name in array for same city.
Thankx in advance, Any suggestion and editing are welcome

You can use the city as the key users from the city as value.
$arr = [];
foreach ($studsInfo as $value) {
$studId = "".$value['_id'];
$indDetail = $industryM->getAllIndustries($studId);
$indusArray['industry'] = iterator_to_array($indDetail);
//$city = $value['city'];
//$name = $value['firstname'];
$arr[$value['city'][] = $value['firstname'];
}
foreach($arr as $k => $v) {
$result[] = array('city' => $k, 'users' => $v);
}

Related

How to compare two values from different foreach loop in PHP?

Here is My codes,
My question is if $company_id from foreach one equal to $Company_id from foreach two then echo company_name.
$ids = array();
$x = array();
$a = array();
foreach($companieslist as $keys=>$company) {
$x[$company->company_id] = [
'id' => $company->company_id,
'name' => $company->company_name
];
}
$entry = $a[$id];
foreach($uploads as $keys=>$general){
$ids[] = $general->Contract_Id;
$c_id = $general->Company_id;
....
Just talking from the performance side, what you should do is extract the company ids from the second batch to an array first, like this
$companies = array();
foreach ( $uploads as $keys => $general ) {
array_push( $companies, $general->Company_id );
}
Now, in the first foreach loop, you can just check if the company id exists in this $companies array, and then decide what to do
foreach($companieslist as $keys=>$company){
if(in_array($company->company_id,$companies)){
echo "Found {$company->company_id}<br/>\n";
}
}

access an array defined by 'pointer'

So I have multiples empty arrays that I want to fill, let's say
$a_tab = [];
$b_tab = [];
$c_tab = [];
I have an array containing some data, let's say
$data = ['a' => 'foo', 'b' => 'bar', 'c' => 'foobar'];
I wanted to be able to do something like this :
foreach($data as $key => $value) {
$tab_name = $key . '_tab'; // so we have a variable that have the same name as one of the array we declared before
$$tab_name[$value] = $value; // this should add 'foo' into $a_tab, 'bar' in $b_tab and 'foobar' in $c_tab
}
But no value is ever added to any array...
Could someone explain me what did I do wrong ?
PS : if you don't want pseudo-code, here is the code that I had when I faced the issue :
// $tab is a parameter of the current function
$done_courses = []; // the array where we are going to put every courses that already have been added in one bifurcation tab
$regex_wz = '/\_werkzoekende/';
$regex_bd = '/\_bediende/';
$regex_op = '/\_outplacement/';
$bifurcation_keys = ['wz_tab' => $regex_wz, 'bd_tab' => $regex_bd, 'op_tab' => $regex_op];
// create the 3 arrays
$wz_tab = [];
$bd_tab = [];
$op_tab = [];
foreach($tab as $key => $value) {
foreach($bifurcation_keys as $tab_name => $regex) {
if(preg_match($regex, $key)) {
$n_k = preg_replace($regex, '', $key);
$$tab_name[$n_k] = $value;
if(!isset($done_courses[$n_k])) {
$done_courses[$n_k] = $n_k;
}
}
}
}
Did you try..
foreach($data as $key => $value) {
${$key.'_tab'}[$value] = $value;
}

Getting formatted result with nested arrays in PHP

I am trying to generate sql statement dynamically with loops but i am not getting any idea on how to do it with html name array.
assuming $name and $message are post arrays ... and assuming length of both will be equal,
following is a method i tried;
<?php
$name = array('name1','name2' );
$mess= array('message1','message2' );
$values = array($name,$mess);
foreach ($values as $key){
foreach ($key as $value){
echo $value.",";
}
}
?>
output is =
name1,name2,message1,message2,
but i want output as =
(name1,message1),(name2,message2),
Edit : I have acess to $values only and I will not be able to determine how many values are going to join in $values ..
like it can be
$values=array($name,$message,$phone);
and the result i want will be
(name1,message1,phone1),(name2,message2,phone2)
My solutions is
Step 1: Loop your $values this will gonna loop every index of your array like $name
foreach($name as $index => $value) {
// do something
}
Step 2: Inside your loop values start with ( which mean wrap your detail in (
echo "(";
Step 3: loop parent array
foreach($values as $key => $arr) {
// do something
}
Step 4: Inside the loop of your parent array display each data according to your index
echo $values[$key][$index];
$key represents the index of your parent array while $index represents the index of your child array like $name
this loop will create data like
(name1,message1,phone1)
and I just add this
if ($key < sizeof(array_keys($values))-1) {
echo ",";
}
to avoid adding , after the last loop
This code will dynamically display array you put inside $values
So your code would be like this
$name = array('name1','name2','name3','name4' );
$mess= array('message1','message2','message3','message4' );
$phone= array('phone1','phone2','phone3','phone4' );
$married= array('yes','no','yes','yes' );
$values = array($name,$mess,$phone);
foreach($name as $index => $value) {
echo "(";
foreach($values as $key => $arr) {
echo $values[$key][$index];
if ($key < sizeof(array_keys($values))-1) {
echo ",";
}
}
echo "),";
}
Demo
or this
$name = array('name1','name2','name3','name4' );
$mess= array('message1','message2','message3','message4' );
$phone= array('phone1','phone2','phone3','phone4' );
$values = array($name,$mess,$phone);
foreach($name as $index => $value) {
$join = array();
foreach($values as $key => $arr) {
$join[] = $values[$key][$index];
}
echo "(".implode(",",$join)."),";
}
Demo
$name = array('name1','name2' );
$mess = array('message1','message2' );
foreach ($names as $k => $v){
echo "(".$v.",".$mess[$k]."),";
}
Try this, you not need two foreach loop, only use foreach loop and pass key to other array and get value
$name = array('name1','name2' );
$mess= array('message1','message2' );
$values = array($name,$mess);
foreach ($name as $keys => $vals)
{
echo "(".$vals.",".$mess[$keys]."),";
}
DEMO
You can use arrap_map() function in order to join two array. Here is reference http://php.net/manual/en/function.array-map.php
<?php
$name = array('name1','name2' );
$mess= array('message1','message2' );
$value = array_map(null, $name, $mess);
print_r($value);
?>

How to parse array from MySQL column in PHP

I have column extra_fields in table.
In column i have array, and I need to parse it
[{"id":"1","value":"fdsds"},{"id":"2","value":"\/images\/powered_by.png"},{"id":"3","value":"fdsfdsfdsfds"},{"id":"4","value":"<p>fdsfdsfdsfds<\/p>"}]
Try to do it with this code,
$extrafields = array();
foreach($this->item->extra_fields as $item)
{
$extrafields[$item->id] = $item->value;
}
but return empty string or...I don't know what
it is unclear as to what you want to achieve but here you go:
$test = json_decode('[{"id":"1","value":"fdsds"},{"id":"2","value":"\/images\/powered_by.png"},{"id":"3","value":"fdsfdsfdsfds"},{"id":"4","value":"<p>fdsfdsfdsfds<\/p>"}]');
$extrafields = array();
foreach ($test as $key => $item) {
$extrafields[$item->id] = $item->value;
}

Create an array with duplicated value from an array (PhP)

I want to create an new array with duplicated MAX value from an array
and put other duplicate value in an other array
$etudiant = array ('a'=>'2','b'=>'5', 'c'=>'6', 'd'=>'6', 'e'=>'2');
and i want this result
$MaxArray = array ('c'=>'6', 'd'=>'6');
$otherarray1 = array ('a'=>'2', 'e'=>'2');
Thank you !
First, find the maximum value:
$etudiant = array ('a'=>'2','b'=>'5', 'c'=>'6', 'd'=>'6', 'e'=>'2');
$maxValue = max($etudiant);
Second, find values that appear more than once:
$dups = array_diff_assoc($etudiant, array_unique($etudiant));
Lastly, check the original arrays for values matching either $maxValue or values that are listed in $dups:
$MaxArray = $OtherArray = $ElseArray = array();
foreach ($etudiant as $key => $value) {
if ($value == $maxValue) {
$MaxArray[$key] = $value;
} else if (in_array($value, $dups)) {
$OtherArray[$key] = $value;
} else {
$ElseArray[$key] = $value;
}
}
You'll get:
$MaxArray: Array
(
[c] => 6
[d] => 6
)
$OtherArray: Array
(
[a] => 2
[e] => 2
)
Note: I wasn't sure if you wanted the $MaxArray to contain the maximum value elements only if it appears more than once in the source array. If so, just change the max call to:
$maxValue = max($dups);
You can use array_values(array_intersect($array1, $array2)) to get duplicated values, and then make a loop to capture the keys which have those values and store them into another array.
$dups = array_values(array_intersect($array1, $array2))
$max = max($dups);
$result = array();
foreach ($array1 as $key => $value){
if (in_array($value, $dups)) {
$result[$key] = $value;
}
}
foreach ($array2 as $key => $value){
if (in_array($value, $dups)) {
$result[$key] = $value;
}
}
$maxArray = array();
foreach ($dups as $key => $value) {
if ($value == $max){
$maxArray[$key] = $value;
}
}
// results are in $dups and $maxArray
If you are looking to find elements with the min and max values from an array, the following will work.
// get min keys
$min_value = min($etudiant);
$min_keys = array_keys($etudiant, $min_value);
// get max keys
$max_value = max($etudiant);
$max_keys = array_keys($etudiant, $max_value);
You could then either rebuild your example arrays with these keys in a loop. Or access them directly, i.e. $etudiant[$min_keys].
Check out the documentation for array_keys, min, max

Categories