Array
(
[0] => Array
(
[source_name] => src_email_24
[suggested_by] => Sameer
[email_id] => sameer.m#blueoceanmi.com
[medium_name] => Email
)
[1] => Array
(
[source_name] => src_email_24
[suggested_by] => Sameer
[email_id] => sameer.m#blueoceanmi.com
[medium_name] => Display
)
)
And if the source_name and medium_name are same then i want the below output
how can i merge the multi dimensional aaray into one array.Any help would be of great help.
Array
(
[0] => Array
(
[source_name] => src_email_24
[suggested_by] => Sameer
[email_id] => sameer.m#blueoceanmi.com
[medium_name] => Email,Display
)
)
hope source_name and email address instead source_name and medium_name; also you should have only one record for a specific email on new data set
<?php
$originalDataSet = [
[
'source_name' => 'src_email_24',
'suggested_by' => 'Sameer',
'email_id' => 'sameer.m#blueoceanmi.com',
'medium_name' => 'Email'
],
[
'source_name' => 'src_email_24',
'suggested_by' => 'Sameer',
'email_id' => 'sameer.m#blueoceanmi.com',
'medium_name' => 'Display'
]
];
$processedDataSet = getProcessedDataFromOriginalDataSet($originalDataSet);
function getProcessedDataFromOriginalDataSet($originalDataSet = []) {
$processedDataSet = [];
foreach ($originalDataSet as $data) {
if (isset($processedDataSet[$data['email_id']])) {
if ($processedDataSet[$data['email_id']]['source_name'] == $data['source_name'] /* && other conditions*/) {
//change only relevant values
}
} else {
$processedDataSet[$data['email_id']] = $data;
}
}
return $processedDataSet;
}
Otherwise something like this
function getProcessedDataFromOriginal($originalDataSet = []) {
$processedDataSet = [];
foreach ($originalDataSet as $originalData) {
$isAdded = 0;
foreach ($processedDataSet as $processedData) {
if ($processedData['source_name'] == $originalData['source_name'] /* && other conditions*/) {
// make changes on processed data set
$isAdded = 1;
break;
}
}
if (!$isAdded) {
$processedData[] = $originalData;
}
}
return $processedDataSet;
}
Related
I've an array on php that will return a lot of keys->values, like this:
Array
[0] => Array
(
[value] => 405
[information] => some information1
)
[1] => Array
(
[value] => 500
[information] => some information2
)
[2] => Array
(
[value] => 700
[information] => some information3
)
the values are numbers, i need to collect all the values, check the first one that will be >= $determinedvalue and then return the value "information" for this exactly array, is this even possible? I know i can do this if i create a temp table on my database, but i dont want to.
To be more clearly, when my value is "430" it will return me "some information2".
I've searched a lot on google but by now i dont know if this is even possible.
Appreciate any help.
This is a sample on how to do that. Comments in code can be used to explain the execution.
// Sample Array
$arr = array(
array
(
"value" => 405,
"information" => "some information1"
),
array
(
"value" => 500,
"information" => "some information2"
),
array
(
"value" => 700,
"information" => "some information3"
)
);
// Sample Number
$numberToCheck = 430;
// Sub Array To Assign
$subArray = array();
// Loop Through Outer Array
for ( $i = 0; $i < sizeof($arr); $i++)
{
// If Value In Array > Number Check
if ( $arr[$i]['value'] >= $numberToCheck )
{
$subArray = $arr[$i]; // Assign Sub Array
$i = sizeof($arr); // This is Used to Exit For Loop
}
}
print_r($subArray); // Print
Working runnable code: https://tech.io/snippet/QJ93AwV
Code snippent with comments:
<?php
/**
* Helper class for stable sort alogithms
* #see https://github.com/vanderlee/PHP-stable-sort-functions
* Class StableSort
*/
class StableSort
{
static public function usort(array &$array, $value_compare_func)
{
$index = 0;
foreach ($array as &$item) {
$item = array($index++, $item);
}
$result = usort($array, function ($a, $b) use ($value_compare_func) {
$result = call_user_func($value_compare_func, $a[1], $b[1]);
return $result == 0 ? $a[0] - $b[0] : $result;
});
foreach ($array as &$item) {
$item = $item[1];
}
return $result;
}
}
$array = [
// added for test sorting
[
'value' => 9999,
'information' => 'some information-1',
],
[
'value' => 1200,
'information' => 'some information0',
],
// \added for test sorting
[
'value' => 405,
'information' => 'some information1',
],
// added for test sorting stability
[
'value' => 405,
'information' => 'some information1.2',
],
[
'value' => 405,
'information' => 'some information1.1',
],
// \added for test sorting stability
[
'value' => 500,
'information' => 'some information2',
],
[
'value' => 700,
'information' => 'some information3',
],
];
// sort array
$determinedvalue = 430;
StableSort::usort($array, function ($item1, $item2) {
if ($item1['value'] == $item2['value']) return 0;
return $item1['value'] < $item2['value'] ? -1 : 1;
});
// then select the first element by condition
$res = null;
foreach($array as $v) {
if($v['value'] >= $determinedvalue) {
$res = $v['information'];
break;
}
}
// for testing
print $res;
$number = 430;
$array = Array
[0] => Array
(
[value] => 405
[information] => some information1
)
[1] => Array
(
[value] => 500
[information] => some information2
)
[2] => Array
(
[value] => 700
[information] => some information3
)
$firstArray = $array[0];
$secondArray = $array[1];
$threeArray = $array[2];
function selectValueFromArrayRange ($number, $start, $end, $value, $infomation)
{
$startValue = $start[$value];
$endValue = $end[$value];
if ( in_array($number, range($startValue, $endValue)) ) {
return $end[$infomation];
}
}
selectValueFromArrayRange($number, $firstArray, $secondValue, 'value', 'infomation')
How can i merge array with the same value?
I have three array which are $participants, $conferance_participants and $contacts
i want to compare values with this three array and merge
for example :
if $participants['calleridnum'] == $conferance_participants['uid'] == $contacts['name']
i want the output to be like this :
Array
(
[0] => Array
(
[calleridnum] => 1
[test] => yay
[uid] => 1
[channel] => deze
[name] => 1
[limit] => 1
)
)
this is my code so far:
<?php
$participants = [
[ 'calleridnum' => 1,
'test' => 'yay'
]
];
$conferance_participants = [
[ 'uid' => 1,
'test' => 'yay2',
'channel' => 'deze'
]
];
$contacts = [
[ 'name' => 1,
'test' => 'yay2',
'limit' => 1
]
];
foreach ($participants as $participant=>$p) {
foreach ($conferance_participants as $conferance_participant=>$c) {
foreach ($contacts as $contact=>$cs) {
if (($p['calleridnum'] == $c['uid']) && ($c['uid'] == $cs['name'])) {
foreach ( $c as $key=>$val ) {
if (!isset($p[$key])) {
$participants[$participant][$key] = $val;
}
}
}
}
}
}
print_r( $participants );
?>
Try to call array_merge() , but you still have to consider the different values with the same key (eg. the values of key 'test' )
if (($p['calleridnum'] == $c['uid']) && ($p['uid'] == $c['name'])) {
$participants[$participant] = array_merge(
$participants[$participant],
$conferance_participants[$conferance_participant],
$contacts[$contact]
);
}
I have an array that looks like this:
[0] => Array
(
[name] => typeOfMusic
[value] => this_music_choice
)
[1] => Array
(
[name] => myMusicChoice
[value] => 9
)
[2] => Array
(
[name] => myMusicChoice
[value] => 8
)
I would like to reform this into something with roughly the following structure:
Array(
"typeOfMusic" => "this_music_choice",
"myMusicChoice" => array(9, 8)
)
I have written the following but it doesn't work:
foreach($originalArray as $key => $value) {
if( !empty($return[$value["name"]]) ){
$return[$value["name"]][] = $value["value"];
} else {
$return[$value["name"]] = $value["value"];
}
}
return $return;
I've tried lots of different combinations to try and get this working. My original array could contain several sets of keys that need converting to arrays (i.e. it's not always going to be just "myMusicChoice" that needs converting to an array) ?
I'm getting nowhere with this and would appreciate a little help. Many thanks.
You just need to loop over the data and create a new array with the name/value. If you see a repeat name, then change the value into an array.
Something like this:
$return = array();
foreach($originalArray as $data){
if(!isset($return[$data['name']])){
// This is the first time we've seen this name,
// it's not in $return, so let's add it
$return[$data['name']] = $data['value'];
}
elseif(!is_array($return[$data['name']])){
// We've seen this key before, but it's not already an array
// let's convert it to an array
$return[$data['name']] = array($return[$data['name']], $data['value']);
}
else{
// We've seen this key before, so let's just add to the array
$return[$data['name']][] = $data['value'];
}
}
DEMO: https://eval.in/173852
Here's a clean solution, which uses array_reduce
$a = [
[
'name' => 'typeOfMusic',
'value' => 'this_music_choice'
],
[
'name' => 'myMusicChoice',
'value' => 9
],
[
'name' => 'myMusicChoice',
'value' => 8
]
];
$r = array_reduce($a, function(&$array, $item){
// Has this key been initialized yet?
if (empty($array[$item['name']])) {
$array[$item['name']] = [];
}
$array[$item['name']][] = $item['value'];
return $array;
}, []);
$arr = array(
0 => array(
'name' => 'typeOfMusic',
'value' => 'this_music_choice'
),
1 => array(
'name' => 'myMusicChoice',
'value' => 9
),
2 => array(
'name' => 'myMusicChoice',
'value' => 8
)
);
$newArr = array();
$name = 'name';
$value = 'value';
$x = 0;
foreach($arr as $row) {
if ($x == 0) {
$newArr[$row[$$name]] = $row[$$value];
} else {
if (! is_array($newArr[$row[$$name]])) {
$newArr[$row[$$name]] = array();
}
array_push($newArr[$row[$$name]], $row[$$value]);
}
$x++;
}
I need to create a similar array to this:
$need = Array(
"smsSend" => Array(
"account" => Array(
"user" => 123,
"password" => "xxxxxx",
"profile" => 123456
)
),
"smsConfig" => Array
(
"region" => Array
(
"locale" => "es_ES",
"timezone" => "America/Bogota"
),
"send" => Array
(
"from" => "9:00:00",
"to" => "21:00:00"
),
"sms" => Array
(
"channel" => "SMS",
"from" => "LINIO",
)
),
"templateConfig" => Array
(
"template" => Array
(
"postpago" => 1111,
"prepago" => 0010,
"notificar" => 1112
)
),
"fieldsConfig" => Array
(
"fields" => Array
(
"nombre" => "firstname",
"carrier" => "nome_transportadora",
"track" => "track",
"cantidad" => "total_depois_de_impostos"
)
),
"serverConfig" => Array
(
"test" => "http://miportal",
"prod" => "",
"mode" => "test",
"adapter" => "curl",
"type" => "post",
"telephone" => "12345"
),
"fields" => Array
(
"sms" => Array
(
"address" => "mobile_phone"
),
"email" => Array
(
"address" => "email_cliente"
)
)
);
From this arrangement to receive from $_POST:
$post = Array(
"smsSend" => Array(
"account" => Array(
"user:123",
"password:xxxxxx",
"profile:123456"
)
),
"smsConfig" => Array
(
"region" => Array
(
"locale:es_ES",
"timezone:America/Bogota"
),
"send" => Array
(
"from:9:00:00",
"to:21:00:00"
),
"sms" => Array
(
"channel:SMS",
"from:LINIO",
)
),
"templateConfig" => Array
(
"template" => Array
(
"postpago:1111",
"prepago:0010",
"notificar:1112"
)
),
"fieldsConfig" => Array
(
"fields" => Array
(
"nombre:firstname",
"carrier:nome_transportadora",
"track:track",
"cantidad:total_depois_de_impostos"
)
),
"serverConfig" => Array
(
"test:http://miportal",
"prod:",
"mode:test",
"adapter:curl",
"type:post",
"telephone:12345"
),
"fields" => Array
(
"sms" => Array
(
"address:mobile_phone"
),
"email" => Array
(
"address:email_cliente"
)
)
);
The problem is the cycle to assemble items of the parent, I use tree function to create levels:
function createLevel1($array_data) {
$array_push = array();
foreach ($array_data as $key_l1 => $elem_l1) {
array_push($array_push[$key_l1], "");
createLevel2($elem_l1, $array_push, $key_l1);
// print_r($resl1);
}
return $array_push;
}
function createLevel2($elemento_array, $push_array, $parent_key) {
foreach ($elemento_array as $key_l2 => $elem_l2) {
if (is_array($elem_l2)) {
$push_array[$parent_key][$key_l2] = "";
createLevel3($elem_l2, $push_array, $parent_key, $key_l2);
} else {
$items = explode("::", $elem_l2);
$push_array[$parent_key][$items[0]] = $items[1];
}
}
return $push_array;
}
function createLevel3($elemento_array, $push_array, $parent_key, $parentl2_key) {
$push_array[$parent_key][$parentl2_key] = "";
foreach ($elemento_array as $key_l3 => $elem_l3) {
if (is_array($elem_l3)) {
createLevel3($elem_l3, $push_array, $parent12_key, $key_l3);
} else {
$items = explode("::", $elem_l3);
$push_array[$parent_key][$parentl2_key][$items[0]] = $items[1];
}
}
return $push_array;
}
$parameter = $_POST['postData'];
#$info = createLevel1($parameter);
print_r($parameter);
The value of the parameter is array $post, the problem is when I print the result $info like this, the option is blank.:
Array
(
[smsSend] =>
[smsConfig] =>
[templateConfig] =>
[fieldsConfig] =>
[serverConfig] =>
[fields] => Array
(
[sms] =>
[email] =>
)
)
$need = array();
foreach ($post as $key => $value) {
if (is_array($value)) {
$need[$key] = $value;
foreach ($value as $key2 => $value2) {
if (is_array($value2)) {
foreach ($value2 as $key3 => $value3) {
if (is_array($value3)) {
} elseif (strpos($value3, ':') !== FALSE) {
$tmp3 = explode(':', $value3);
$need[$key][$key2][$tmp3[0]] = $tmp3[1];
unset($need[$key][$key2][$key3]);
}
}
} elseif (strpos($value2, ':') !== FALSE) {
$tmp2 = explode(':', $value2);
$need[$key][$tmp2[0]] = $tmp2[1];
unset($need[$key][$key2]);
}
}
}
}
I have wrote this code. I think it is working. But issue is there. when i use explode it divide http://miportal.com also. try another method like strstr. Try it with recursive function.
Here are two example of the format of the Arrays, full code and array content in my code below.
ARRAY 1
[
'version' => '1.0',
'injuries' => [
'timestamp' => 1377702112,
'week' => 1,
'injury' => [
[
'status' => 'Questionable',
'id' => '10009',
'details' => 'Shoulder'
],
[
'status' => 'Questionable',
'id' => '10012',
'details' => 'Ankle'
]
]
]
]
ARRAY 2
[
'version' => '1.0',
'players' => [
'timestamp' => 1377676937,
'player' => [
[
'position' => 'TMDL',
'name' => 'Bills, Buffalo',
'id' => '0251',
'team' => 'BUF'
],
[
'position' => 'TMDL',
'name' => 'Colts, Indianapolis',
'id' => '10009',
'team' => 'IND'
]
]
]
]
What I need to do is sort through both Arrays and finding matching values for the ID key. I need to then combine the values of both arrays into one array so I can print it out on screen. There is two API's provided, one for the injuries report with a player [id] key and the other for the Players Information with [id] keys. Here is how far I have gotten on this problem:
<?php
function injuries_report() {
//Get json files
$injuryData = file_get_contents('http://football.myfa...=1&callback=');
$playerData = file_get_contents('http://football.myfa...L=&W=&JSON=1');
//format json data into an array
$obj1 = json_decode($injuryData, true);
$obj2 = json_decode($playerData, true);
//return print_r($obj1); //print obj1 to see output
return print_r($obj2); //print obj2 to see output
}
?>
<!--get injuries report -->
<pre><?php injuries_report(); ?></pre>
Here's the working code, thanks to Chris:)
$injuryData = file_get_contents('http://football.myfantasyleague.com/2013/export?TYPE=injuries&L=&W=&JSON=1&callback=');
$array1 = json_decode($injuryData, true);
$playerData = file_get_contents('http://football.myfantasyleague.com/2013/export?TYPE=players&L=&W=&JSON=1');
$array2 = json_decode($playerData, true);
function map($x) {
global $array1;
if(isset($x['id'])) {
$id = $x['id'];
$valid = array_filter($array1['injuries']['injury'], create_function('$injury', 'return $injury["id"] == "' . $id .'";'));
if(count($valid) > 0) {
$x = array_merge($x, array_shift($valid));
}
}
return $x;
}
$output = array_map('map', $array2['players']['player']);
echo "<pre>";
print_r($output);
echo "</pre>";
Ok, I'm assuming you want to add injuries to players. The output will be the list of players, with the injuries added (where they apply)
$output = array_map(function($x) use ($array1) {
$id = $x['id'];
$valid = array_filter($array1['injuries']['injury'], function($injury) use ($id) {
return $injury['id'] == $id;
});
if(count($valid) > 0) {
$x = array_merge($x, $valid[0]);
}
return $x;
}, $array2['players']['player']);
print_r($output);
The output is this:
Array
(
[0] => Array
(
[position] => TMDL
[name] => Bills, Buffalo
[id] => 0251
[team] => BUF
)
[1] => Array
(
[position] => TMDL
[name] => Colts, Indianapolis
[id] => 10009
[team] => IND
[status] => Questionable
[details] => Shoulder
)
)
php 5.2
Edit The latest working version:
Oh you are using php 5.2. Here is a php 5.2 version, but it less pretty than the code before:
$injuryData = file_get_contents('http://football.myfantasyleague.com/2013/export?TYPE=injuries&L=&W=&JSON=1&callback=');
$array1 = json_decode($injuryData, true);
$playerData = file_get_contents('http://football.myfantasyleague.com/2013/export?TYPE=players&L=&W=&JSON=1');
$array2 = json_decode($playerData, true);
function map($x) {
global $array1;
if(isset($x['id'])) {
$id = $x['id'];
$valid = array_filter($array1['injuries']['injury'], create_function('$injury', 'return $injury["id"] == "' . $id .'";'));
if(count($valid) > 0) {
$x = array_merge($x, array_shift($valid));
}
}
return $x;
}
$output = array_map('map', $array2['players']['player']);
print_r($output);
The $array1 is global here. Check it here: http://pastebin.com/N3RqtfzN