I have a multidimentional array below in php.
$resultdata[0] = array(
"daynumber" => 15,
"dayname" =>'Tue',
"infomation" => array('baller', 'ROller')
);
$resultdata[1] = array(
"daynumber" => 15,
"dayname" =>'Tue',
"infomation" => array('nomal', 'Goildt')
);
$resultdata[2] = array(
"daynumber" => 24,
"dayname" =>'Thur',
"infomation" => array('Volley', 'Foller')
);
I want to combine the similar dates to form the following result.
$resultdata[0] = array(
"daynumber" => 15,
"dayname" =>'Tue',
"infomation" => array('baller', 'ROller'), array('nomal', 'Goildt')
);
$resultdata[1] = array(
"daynumber" => 24,
"dayname" =>'Thur',
"infomation" => array('Volley', 'Foller')
);
Thanx in advance
I tried using this code but it requies me to convert array to string which i dont want
function combineAndIgnore($result_arr){
$arr = array();
foreach($result_arr as $val){
$item = $val[$key];
foreach($val as $k=>$v){
$arr[$item][$k][] = $v;
}
}
// Combine unique entries into a single array
// and non-unique entries into a single element
foreach($arr as $key=>$val){
foreach($val as $k=>$v){
$field = array_unique($v);
if(count($field) == 1){
$field = array_values($field);
$field = $field[0];
$arr[$key][$k] = $field;
} else {
$arr[$key][$k] = $field;
}
}
}
return $arr;
}
I gave in to the convert to sting option which has worked anyway
<?php
$resultdata[0] = array(
"daynumber" => 15,
"dayname" =>'Tue',
"infomation" => array('baller', 'ROller','','gtk')
);
$resultdata[1] = array(
"daynumber" => 15,
"dayname" =>'Tue',
"infomation" => array('nomal', 'Goildt')
);
$resultdata[2] = array(
"daynumber" => 24,
"dayname" =>'Thur',
"infomation" => array('goon' => 'Volley', 'Foller')
);
$counter = 0;
foreach($resultdata as $veliu){
$newinfo = implode(':*:', $veliu["infomation"]);
$veliu["infomation"] = $newinfo;
$temporryry[$counter] = $veliu;
$counter++;
}
function multiarray_merge($result_arr, $key){
foreach($result_arr as $val){
$item = $val[$key];
foreach($val as $k=>$v){
$arr[$item][$k][] = $v;
}
}
// Combine unique entries into a single array
// and non-unique entries into a single element
foreach($arr as $key=>$val){
foreach($val as $k=>$v){
$field = array_unique($v);
if(count($field) == 1){
$field = array_values($field);
$field = $field[0];
$arr[$key][$k] = $field;
} else {
$arr[$key][$k] = $field;
}
}
}
return $arr;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://fonts.googleapis.com/css?family=Varela+Round" rel="stylesheet">
<style type="text/stylesheet">
font-family: 'Varela Round', sans-serif;
</style>
</head>
<body>
<pre>
<?php
$newarray = multiarray_merge($temporryry, 'daynumber');
$count = 0;
$counte = 0;
foreach($newarray as $vel){
$notin = $vel["infomation"];
if(is_array($notin)){
foreach($notin as $jin){
$reve = explode(":*:", $jin);
$good[$counte] = $reve;
$counte++;
}
}else{
$reve = explode(":*:", $notin);
$good= $reve;
}
$vel["infomation"] = $good;
$finalsolution[$count] = $vel;
$count++;
}
print_r($finalsolution);
?>
</pre>
</body>
</html>
RESULT
Array
(
[0] => Array
(
[daynumber] => 15
[dayname] => Tue
[infomation] => Array
(
[0] => Array
(
[0] => baller
[1] => ROller
[2] =>
[3] => gtk
)
[1] => Array
(
[0] => nomal
[1] => Goildt
)
)
)
[1] => Array
(
[daynumber] => 24
[dayname] => Thur
[infomation] => Array
(
[0] => Volley
[1] => Foller
)
)
)
Here's a quick-and-dirty solution to your unique use-case which you may as well Quick-T3st here:
<?php
$strJson = '[
{
"daynumber" :15,
"dayname" :"Tue",
"infomation" :["baller","ROller"]
},
{
"daynumber" :15,
"dayname" :"Tue",
"infomation" :["nomal","Goildt"]
},
{
"daynumber" :24,
"dayname" :"Thur",
"infomation" :["Volley","Foller"]
}
]';
function arrayBlend($jsonData){
$resultData = json_decode($jsonData, true);
$arrAll = [];
foreach($resultData as $data){
if(is_array($data)){
$arrAll[] = $data;
}
}
foreach($arrAll as $iCount=>&$arr){
$dayNum = $arr['daynumber'];
$dayName = $arr['dayname'];
$prev = ($iCount>0) ? $arrAll[$iCount-1] : null;
if($prev['daynumber'] == $dayNum && $prev['dayname'] == $dayName){
$arr['infomation'] = [ $prev['infomation'], $arr['infomation']];
unset($arrAll[$iCount-1]);
}
}
return $arrAll;
}
var_dump( arrayBlend($strJson) );
The var_dump() above yieds:
array:2 [
1 => array:3 [
"daynumber" => 15
"dayname" => "Tue"
"infomation" => array:2 [
0 => array:2 [
0 => "baller"
1 => "ROller"
]
1 => array:2 [
0 => "nomal"
1 => "Goildt"
]
]
]
2 => array:3 [
"daynumber" => 24
"dayname" => "Thur"
"infomation" => array:2 [
0 => "Volley"
1 => "Foller"
]
]
]
Related
I have 3 array like
$arr = [
"color" => [["name"=>"red"]],
"size" => [["name"=>"18 inch"], ["name"=>"15 inch"]],
"type" => [["name"=>"plastic"]]
]
$combo = array();
foreach ($arr['size'] as $size) {
foreach($arr['color'] as $color){
foreach ($arr['type'] as $type) {
$variant = json_encode(['size' => $size->name, 'color' =>
$color->name, 'type' => $type->name]);
array_push($combo,$variant);
}
}
}
echo $combo;
// result
0 => "{"size":"15 inch","color":"yellow","type":"metal"}"
1 => "{"size":"18 inch","color":"yellow","type":"plastic"}"
It works properly but but there is can be less or more variants. How can I handle this.
For example
$arr = [
"size" => [["name"=>"18 inch"], ["name"=>"15 inch"]],
"type" => [["name"=>"plastic"]]
]
Or
$arr = [
"color" => [["name"=>"red"]],
"size" => [["name"=>"18 inch"], ["name"=>"15 inch"]],
"type" => [["name"=>"plastic"]],
"brand" => [['name' => 'something']],
]
For what i understand, you have to combine the arrays of properties into one array of
object.
I have to leave now, but if you need a explanation leave a comment and i updated the answers
$arr = [
"color" => [["name"=>"red"],['name'=>'yellow']],
"size" => [["name"=>"18 inch"], ["name"=>"15 inch"]],
"type" => [["name"=>"plastic"]],
"brand" => [['name' => 'something']],
];
function runFor($arr ,&$array, $keys,$index,&$positions){
foreach ($arr[$keys[$index]] as $key => $espec){
$positions[$keys[$index]] = $key;
if($index + 1 < count($keys)){
runFor($arr,$array,$keys, $index+1,$positions);
}else{
$item = (object)[];
foreach ($keys as $key){
$item->$key = $arr[$key][$positions[$key]]['name'];
}
array_push($array,$item);
}
unset($positions[$keys[$index]]);
}
}
$array = array();
$keys = array_keys($arr);
$positions = [];
runFor($arr,$array,$keys,0,$positions);
$combo = array();
foreach ($array as $item){
array_push($combo,json_encode($item));
}
var_dump($combo);
$arrayDif = array();
$arrayDif[] = array('employer' => $employer,
'comment' => $comment,
'value' => $resultValue);
Filling in from a loop.
Below is the array that I have filled up. I need to be able to find a match by the 'employer' and 'comment' and extract the value, so I can re-update this value.
Array
(
[0] => Array
(
[employer] => Albury-Wodonga
[comment] => allOtherMembers
[value] => 7
)
[1] => Array
(
[employer] => Albury-Wodonga
[comment] => associateMembers
[value] => 1
)
One command to extract and re-update the value, I suggest to use foreach loop
<?php
$arrayDif = array();
$arrayDif[] = array('employer' => "AAA", 'comment' => "comment 1", 'value' => "1");
$arrayDif[] = array('employer' => "BBB", 'comment' => "comment 2", 'value' => "2");
$arrayDif[] = array('employer' => "CCC", 'comment' => "comment 3", 'value' => "3");
// function for setting the value or returning the value
// notice the $array here is a reference to the real array
function func(&$array, $employer, $comment, $value = ''){
// $v is also a reference
foreach ($array as $k => &$v) {
if($v['employer'] == $employer && $v['comment'] == $comment) {
if(empty($value)) {
return $v['value'];
} else {
$v['value'] = $value;
}
}
}
return "Not Found.";
}
//update
func($arrayDif, 'AAA', 'comment 1', "123123");
//search
echo func($arrayDif, 'AAA', 'comment 1');
?>
Not sure if this is what you are looking for but here you go. I would use a function and simple loop.
<?php
$arrayDif = array();
$arrayDif[] = array(
array('employer' => "Albury-Wodonga", 'comment' => "allOtherMembers", 'value' => "1 star"),
array('employer' => "Employer2", 'comment' => "Good Job", 'value' => "2 stars"),
array('employer' => "Employer3", 'comment' => "Smart", 'value' => "3 stars")
);
// Function for searching the array for the matches and returning the value of the match.
function SearchMe($array, $searchEmployer, $searchComment){
for($i = 0; $i < count($array); $i++){
for($j = 0; $j < count($array[$i]); $j++){
if(
$array[$i][$j]["employer"] == $searchEmployer &&
$array[$i][$j]["comment"] == $searchComment
){
return $array[$i][$j]["value"];
}
}
}
return "No Match";
}
echo SearchMe($arrayDif, "Albury-Wodonga", "allOtherMembers");
?>
I have a simple php array for location postcode and their name. I want compress 'code' by 'name'. This code from WooCommerce database zones.
$new_arr = [
[
'name' => 'Jambi Selatan',
'code' => '36139',
'code_name' => '36139 - Jambi Selatan'
],
[
'name' => 'Jambi Selatan',
'code' => '36137',
'code_name' => '36137 - Jambi Selatan'
],
[
'name' => 'Bagan Pete',
'code' => '36129',
'code_name' => '36129 - Bagan Pete'
],
[
'name' => 'Bagan Pete',
'code' => '36127',
'code_name' => '36127 - Bagan Pete'
]
];
I want get final result combined by 'name' and 'code' like this: i try array_unique method but not working.
Array (
[0] => Array
(
[name] => Jambi Selatan
[code] => 36139, 36137
[code_name] => 36139, 36139 - Jambi Selatan
)
[1] => Array
(
[name] => Bagan Pete
[code] => 36127, 36129
[code_name] => 36127, 36129 - Bagan Pete
)
)
I try this method, but not fix at 'code_name'
$out = array();
foreach ($new_arr as $key => $value){
if (array_key_exists($value['name'], $out)){
$out[$value['name']]['code'] .= ', '.$value['code'];
} else {
$out[$value['name']] = array(
'name' => $value['name'],
'code' => $value['code'],
'code_name' => $value['code'] . ' - ' . $value['name']
);
}
}
$out = array_values($out);
print_r($out);
You have to check duplicate name by in_array and update exist array value .If not exist insert that value to $out array .
$out = array();
foreach($new_arr as $k=>$v) {
//empty array state
if(count($out) == 0) {
$out[] = $v;
continue;
}
foreach ($out as $key => $value) {
if(in_array($v["name"],$value)) {
$out[$key]["code"] .= ",".$v["code"];
//for the code_name output as OP described
$nn = explode("-", $value["code_name"]);
$l = count($nn) - 1;
unset($nn[$l]);
$out[$key]["code_name"] = implode($nn).",".$v["code_name"];
break;
} else {
if((count($out)-1) == $key) {
$out[] = $v;
}
}
}
}
var_dump($out);
For someone have problem like me, this method for fix it:
$out = array();
foreach ($new_arr as $key => $value){
if (array_key_exists($value['name'], $out)){
$out[$value['name']]['code'] .= ', '.$value['code'];
$out[$value['name']]['code_name'] .= ', '.$value['code'] . ' - ' . $value['name'];
} else {
$out[$value['name']] = array(
'name' => $value['name'],
'code' => $value['code'],
'code_name' => $value['code']
);
}
}
$out = array_values($out);
print_r($out);
Final result;
Array
(
[0] => Array
(
[name] => Jambi Selatan
[code] => 36139, 36137
[code_name] => 36139, 36137 - Jambi Selatan
)
[1] => Array
(
[name] => Bagan Pete
[code] => 36129, 36127
[code_name] => 36129, 36127 - Bagan Pete
)
)
Please try below one as another approach:
<?php
$arr = Array (
Array
(
'name' => 'Jambi Selatan',
'code' => '36139',
'code_name' => '36139 - Jambi Selatan'
),
Array
(
'name' => 'Jambi Selatan',
'code' => '36137',
'code_name' => '36137 - Jambi Selatan'
),
Array
(
'name' => 'Bagan Pete',
'code' => '36129',
'code_name' => '36129 - Bagan Pete'
),
Array
(
'name' => 'Bagan Pete',
'code' => '36127',
'code_name' => '36127 - Bagan Pete'
)
);
$newarr = array();
$finalArr = array();
foreach($arr as $aa) {
$newarr[$aa['name']][] = $aa;
}
foreach($newarr as $kk => $bb) {
foreach($bb as $cc) {
$finalArr[$kk]['name'] = $cc['name'];
if(isset($finalArr[$kk]['code'])) {
$finalArr[$kk]['code'] = $finalArr[$kk]['code'].','.$cc['code'];
} else {
$finalArr[$kk]['code'] = $cc['code'];
}
if(isset($finalArr[$kk]['code_name'])) {
$finalArr[$kk]['code_name'] = $finalArr[$kk]['code_name'].','.$cc['code_name'];
} else {
$finalArr[$kk]['code_name'] = $cc['code_name'];
}
}
}
echo "<pre>";
print_r($finalArr);
echo "</pre>";
?>
Definitely avoid any suggestions that use more than one loop to group and concatenate the data.
I do endorse #Opsional's snippet. An alternative approach is to push reference variables into the result array, then only concatenate comma-separated values to the appropriate reference variable.
Code: (Demo)
$result = [];
foreach ($arr as $row) {
if (!isset($ref[$row['name']])) {
$ref[$row['name']] = $row;
$result[] = &$ref[$row['name']];
} else {
$ref[$row['name']]['code'] .= ', ' . $row['code'];
$ref[$row['name']]['code_name'] .= ', ' . $row['code_name'];
}
}
var_export($result);
For any purist developers that insist on destroying references, call unset($ref) after the loop.
Here is a streamlined version of #Opsional's snippet: (Demo)
$result = [];
foreach ($arr as $row) {
if (!isset($result[$row['name']])) {
$result[$row['name']] = $row;
} else {
$result[$row['name']]['code'] .= ', ' . $row['code'];
$result[$row['name']]['code_name'] .= ', ' . $row['code_name'];
}
}
var_export(array_values($result));
I have two arrays
$Array_1 = array(
'ID_1' => 'Michael',
'ID_2' => 'Jerry',
'ID_3' => 'Tony',
'ID_4' => 'Roger',
);
$Array_2 = array(
'ID_1' => 'Chef',
'ID_2' => 'Mechanic',
'ID_3' => 'Cook',
'ID_4' => 'Dealer',
);
I wish to merge them on the ID column and have my final array be in this form
$employees = array(
array(
'name' => 'Jason',
'occupation' => 'Chef'
),
array(
'name' => 'Mike',
'occupation' => 'Mechanic'
),
...
);
I know I can array combine them like below:
$new_array = array_combine(array_values($Array_1), array_values($Array_2));
but how would I add the titles "Name": and "Occupation":
Can you try this,
$Employees = array();
foreach($Array_1 as $key=>$value):
$Employees['Employees'][] = array('Name'=>$value, 'Occupation'=>$Array_2[$key]);
endforeach;
echo "<pre>";
print_r($Employees);
echo "</pre>";
echo json_encode($Employees);
OP:
{"Employees":[{"Name":"Jason","Occupation":"Chef"}, {"Name":"Mike","Occupation":"Mechanic"}]}
i dont know how the array look. but you can try my two solution
First solution
$array1 = array("id" => array("id1", "id2", "id3"), "names" => array("name1", "name2", "name3"));
$array2 = array("id" => array("id1", "id2", "id3"), "occupation" => array("occupation1", "occupation2", "occupation3"));
$filter_array = array("employees" => array());
foreach ($array1["id"] as $index => $key) {
$employee = array();
$occupation = in_array($key, $array2["id"]) ? $array2["occupation"][$index] : false;
if ($occupation === false) {
continue;
}
$employee["name"] = $key;
$employee["occupation"] = $occupation;
array_push($filter_array["employees"], $employee);
}
echo "<pre>" . print_r($filter_array, true) . "</pre>";
Second Solution
$array1 = array("id1" => array("names" => "name1"), "id2" => array("names" => "name2"), "id3" => array("names" => "name3"));
$array2 = array("id1" => array("occupation" => "occupation1"), "id2" => array("occupation" => "occupation2"), "id3" => array("occupation" => "occupation3"));
$filter_array = array("employees" => array());
foreach ($array1 as $key => $value) {
$employee = array();
if (!isset($array2[$key])) {
continue;
}
$employee["name"] = $value["names"];
$employee["occupation"] = $array2[$key]["occupation"];
array_push($filter_array["employees"], $employee);
}
echo "<pre>" . print_r($filter_array, true) . "</pre>";
i hope my code can help.
you can try this
$Array_1 = array(
'ID_1' => 'Michael',
'ID_2' => 'Jerry',
'ID_3' => 'Tony',
'ID_4' => 'Roger',
);
$Array_2 = array(
'ID_1' => 'Chef',
'ID_2' => 'Mechanic',
'ID_3' => 'Cook',
'ID_4' => 'Dealer',
);
$filter_array = array("employees" => array());
foreach($Array_1 as $key => $value){
$employee = array();
if(!isset($Array_2[$key])){ continue; }
$employee["name"] = $value;
$employee["occupation"] = $Array_2[$key];
array_push($filter_array["employees"], $employee);
}
EDIT 2
Aah, now I see the phpfiddle in the comments and the edit to the OP. So, the ID is already the key of the array? ... Then just do
foreach($Array_1 as $key_1 => $value_1) {
$new_Array[$key_1]['Names'] = $Array_1['Names'];
}
foreach($Array_2 as $key_2 => $value_2) {
$new_Array[$key_2]['Occupation'] = $Array_2['Occupation'];
}
use array_walk . It runs a function per each array item .combine them in the function .
I have script like this
foreach ($onerow as $onekey => $dt ){
$arr = array();
foreach($row as $classkey => $classfoto):
$cek_class_foto = explode("/",$classfoto->name);
if($dt->foto_naam!=$cek_class_foto[1]){
$arr = array($dt->foto_naam);
print_r(array_unique($arr));
}
endforeach;
}
the output like this
Array ( [0] => _b101203.jpg )
Array ( [0] => _b101203.jpg )
my question is, how to remove this duplicates array?
Thank you
You are overwriting $arr for each iteration.
foreach ($onerow as $onekey => $dt ){
$arr = array();
foreach($row as $classkey => $classfoto):
$cek_class_foto = explode("/",$classfoto->name);
if($dt->foto_naam!=$cek_class_foto[1]){
$arr[] =$dt->foto_naam;
}
endforeach;
}
$arr = array_unique($arr);
$array1 = Array
(
'0' => Array
(
'messageId' => 9,
'userId' => 47,
'petId' => 68,
'message' => 'how hello',
'senderId' => 48,
'senderPetId' => 66,
'messageCreateTime' => '2015-07-31 11:44:59'
),
'1' => Array
(
'messageId' => 8,
'userId' => 49,
'petId' => 69,
'message' => 'pppppppppp',
'senderId' => 48,
'senderPetId' => 67,
'messageCreateTime' => '2015-07-31 11:15:16'
),
'2' => Array
(
'messageId' => 6,
'userId' => 48,
'petId' => 67,
'message' => 'gggg',
'senderId' => 49,
'senderPetId' => 69,
'messageCreateTime' => '2015-07-31 11:13:42'
),
'3' => Array
(
'messageId' => 2,
'userId' => 48,
'petId' => 67,
'message' => 'aaaaaaaa',
'senderId' => 47,
'senderPetId' => 68,
'messageCreateTime' => '2015-07-31 11:15:33'
)
);
/* code for removing last duplicate array within result array by KS */
/* matching between : userId, petId, senderId, senderPetId */
$temp_array = array();
$i = 0;
foreach($array1 as $key=>$value)
{
$FLAG = FALSE;
$temp_array = $array1[$key];
if($i==0)
{
$final_array[] = $temp_array;
}
else
{
for($j=0;$j<count($final_array);$j++)
{
if(($final_array[$j]['userId']==$temp_array['userId'] && $final_array[$j]['petId']==$temp_array['petId'] && $final_array[$j]['senderId']==$temp_array['senderId'] && $final_array[$j]['senderPetId']==$temp_array['senderPetId']) ||
($final_array[$j]['userId']==$temp_array['senderId'] && $final_array[$j]['petId']==$temp_array['senderPetId'] && $final_array[$j]['senderId']==$temp_array['userId'] && $final_array[$j]['senderPetId']==$temp_array['petId']))
{
$FLAG = TRUE;
}
}
if($FLAG == FALSE){
$final_array[] = $temp_array;
}
}
$i++;
}
print('<pre>');
print_r($final_array);
enter code here