This seems like a relatively easy thing to do but I'm struggling a bit. Here is a bit of backstory. I'm currently making a schedule of events based off a web service.
Because of the way it outputs data I've been creating and rearranging the information based off the clients wants/needs.
I've created a time array that basically loops through the open hours in 15 min intervals. Example...
Array
(
[0600] => 0
[0615] => 0
[0630] => 0
[0645] => 0
[0700] => 0
[0715] => 0
[0730] => 0
[0745] => 0
[0800] => 0
[0815] => 0
[0830] => 0
[0845] => 0
[0900] => 0
...etc etc
[2300] => 0
)
Once I've done that I loop(using a foreach) through events and if the time is equal to a key add it to the array. The variables are just items from web service.
$timeArray[date('Hi', $roundStart)] = array(
'e_name' => $eventName,
'e_build_id' => $buildId,
'e_start' => $timeStampS,
'e_end' => $timeStampE,
'e_class' => $eClass,
'e_span' => $fullSpan,
'e_status' => $canCheck,
'e_lanes' => $lanesOpen
);
But I've noticed there is a bug with this and that if you have two events at the same time the last one will override the other one. What I need instead is for the events to be within the same key. So adding two or more arrays to the key.
Let me know if this makes sense?
in your initial array, make the values empty arrays:
Array
(
[0600] => []
...etc etc
[2300] => []
)
then when you assign, just push on the array
$timearray[$time][] = $event;
just make sure you always treat the $timearray indexes as arrays, even if they only contain one (or zero!) events.
good luck!
Just make every entry in your interval array an array
// instead the if condition you can initialize the array in your loop when creating it
if (!is_array($timeArray[date('Hi', $roundStart)])) {
$timeArray[date('Hi', $roundStart)] = array();
}
$timeArray[date('Hi', $roundStart)][] = array(
'e_name' => $eventName,
'e_build_id' => $buildId,
'e_start' => $timeStampS,
'e_end' => $timeStampE,
'e_class' => $eClass,
'e_span' => $fullSpan,
'e_status' => $canCheck,
'e_lanes' => $lanesOpen
);
try this:
Array
(
[0600] => array()
...
and
$timeArray[date('Hi', $roundStart)][] = array(
'e_name' => $eventName,
'e_build_id' => $buildId
...
So instead of setting every hour to 0, better set everything to an empty array in your initial run. Instead of checking against 0, you can then check against an array with 0 length. So basically the same. For your date setting loop, you will now, instead of creating a new array, just push to that array. Something like
array_push($timeArray[date('Hi', $roundStart)], array(
'e_name' => $eventName,
'e_build_id' => $buildId,
'e_start' => $timeStampS,
'e_end' => $timeStampE,
'e_class' => $eClass,
'e_span' => $fullSpan,
'e_status' => $canCheck,
'e_lanes' => $lanesOpen
));
should do the job.
After that, just loop over the dates at any given time and execute them all.
Related
I have an array of channels, so far I know how to return min and max values like this:
// clear from any empty channels
$channels = array_filter($scan['channels']);
// get min/max values
$min = array_keys($channels, min($channels));
$max = array_keys($channels, max($channels));
// this returns the channel name wich is what I need
So far I would like to get the median key (channel) name, how can I achieve this?
// this is the array of channels
Array
(
[chann_1] => 155.755
[chann_2] => 154.61
[chann_3] => 156.719
[chann_4] => 156.727
[chann_5] => 155.797
[chann_6] => 157.615
[chann_7] => 154.257
[chann_8] => 151.724
[chann_9] => 156.549
[chann_10] => 156.594
[chann_11] => 157.56
[chann_12] => 156.405
)
Try this:.
Sort the array.
Get the array keys.
Then half of count of array_keys is the median value. (I added round just in case).
$arr = Array(
"chann_1" => 155.755,
"chann_2" => 154.61,
"chann_3" => 156.719,
"chann_4" => 156.727,
"chann_5" => 155.797,
"chann_6" => 157.615,
"chann_7" => 154.257,
"chann_8" => 151.724,
"chann_9" => 156.549,
"chann_10" => 156.594,
"chann_11" => 157.56,
"chann_12" => 156.405);
Arsort($arr);
//Var_dump($arr);
$keys = array_keys($arr);
Echo $keys[round(count($keys)/2)];
https://3v4l.org/ER3d4
Usearray_search().$max_key=array_search($max,$yourArray);$min_key=array_search($min,$yourArray);$median=$max_key+$min_key/2;of course it depends on your Array size.
Try $median=array_search($max+$min/2,$yourArra);
I have 2 arrays. The first array contains the correct word variants and the second array contains incorrect word variants. I want to write them by combining into one as an array, passing in the wrong version of the words to the key and to the value of the correct version of the word. Then write them to a file and use it. I saved the contents of the array in a file, but with a new record to the same file, all the data is cleared and only new entries are re-written and the old entries are deleted automatically. I want that before writing new data to an array, the array is checked for duplication and if such is not written in the file with the array, then let it be written to the file without clearing the previous data of the file. In general, that will select a file or database for storing more than a billion words. Does the database have the best speed or file?
Example first array:
$uncorrect = array
(
0 => "мувосокори",
1 => "мунаггас",
2 => "мангит",
3 => "мангития",
4 => "мунфачир",
5 => "мунфачира",
6 => "манфиатпарасти",
7 => "манфиатчу",
8 => "манфиатчуи",
9 => "манфиатхох",
10 => "манфи",
.....................
);
Example second array:
$correct = array
(
0 => "мувосокорӣ",
1 => "мунағғас",
2 => "манғит",
3 => "манғития",
4 => "мунфаҷир",
5 => "мунфаҷира",
6 => "манфиатпарастӣ",
7 => "манфиатҷӯ",
8 => "манфиатҷӯӣ",
9 => "манфиатхоҳ",
10 => "манфӣ",
.....................
);
I combined two arrays with this code:
$dict = array_combine($uncorrect, $correct);
Example result my array with data here:
$dict = array (
"мувосокори" => "мувосокорӣ",
"мунаггас" => "мунағғас",
"мангит" => "манғит",
"мангития" => "манғития",
"мунфачир" => "мунфаҷир",
"мунфачира" => "мунфаҷира",
"манфиатпарасти" => "манфиатпарастӣ",
"манфиатчу" => "манфиатҷӯ",
"манфиатчуи" => "манфиатҷӯӣ",
"манфиатхох" => "манфиатхоҳ",
"манфи" => "манфӣ",
"минкор" => "минқор",
.....................................
);
I am writing to a file with this code:
file_put_contents("data.json", json_encode($dict));
I will get the array with this code:
$array = json_decode(file_get_contents("data.json"));
You would be better off using a database for this task.
To solve your issue if you decide to keep with the file storage, the reason you are losing old entries is because you forgot to load them before adding new values.
// more or less something like below
$array = json_decode(file_get_contents("data.json"));
$dict = array_combine($incorrect, $correct);
$newArray = array_merge($array, $dict);
file_put_contents("data.json", json_encode($newArray));
This will not be efficient for billions or rows, especially if it's something that gets loaded every time a user loads a page.
Any time you want to add new items just load the file first, then merge the new items in before saving it again. file_put_contents is going to overwrite whatever was there, so you need to get that data before running that function. Something like this:
$array = json_decode(file_get_contents("data.json"));
$newArray = array(
array( "rightWord" => "wrongWord")
);
$finalArray = array_merge($newArray, $array);
file_put_contents("data.json", json_encode($finalArray));
This is driving me mad.. I have a PHP script that returns an array in the form $key => $value and I want to rename the key so that I can display it in a table header. I saw there are several ways of doing this but I'm not sure they are what I need... Either that or I haven't understood the examples correctly which is the likely problem.
Basically my array keys differ each time I iterate over a foreach loop and also some can be blank. How can I get round this?
The first output might look like this:
'_can_chaccess' => false,
'_can_chown' => false,
'_can_delete' => false,
'_can_modify' => false,
'_can_read' => true,
'assigned_to_name_879' => 'Unassigned',
'id' => 1,
'type' => 'Private::Reporting::DataViewModel::DataView_223_42858',
'type_877' => 'Email',
The next run through, I might get this:
'_can_chaccess' => false,
'_can_chown' => false,
'_can_delete' => false,
'_can_modify' => false,
'_can_read' => true,
'assigned_to_name_793' => 'Consultants',
'id' => 1,
'object_reference_794' => 'CASE-1004',
'summary_795' => 'Deployment of New System for HQ (Project)',
'type' => 'Private::Reporting::DataViewModel::DataView_200_42858',
),
As you can see, some keys rename the same e.g. id, type. But the most important ones that I am interested in change each time e.g. Assigned To Name.
Any ideas?
Where do you receive your data from?
You can either somehow modify the source of your data, so if it were a query (what I do not assume here), you have the SELECT ... AS ... statement.
First you do need to know how to interpret the changing keys. If e.g. "assigned_to_name_879" and "assigned_to_name_793" is the same field, you can define a canonical function, which mapps both inputs to a unique output.
The output of the cannonical function and as well the other array keys can serve as keys for an additional array, which contains the table headers of your output.
So your current array is the value's array, and by hand you define a header's array:
array(
'assigned_to_name_879' => 'Name assignment'
);
This dynamic way of storing the table headers in an array only makes sense if you are using the array twice. Otherwise you could simply write the header in the html-code which you do output.
I've managed to figure it out using the below:
$mappings_array = array();
foreach ($report['data'][0] as $key => $value) {
$workbooks->log('Old Key', $key);
preg_match_all('([^_\d]+)', $key, $new_key);
$workbooks->log('New Key', $new_key);
$str = implode(" ", $new_key[0]);
$capitalised = ucwords($str);
array_push($mappings_array,$capitalised);
}
Maybe it's not the best solution but it works :) I get the following output:
> New array: «array (
0 => 'Can Chaccess',
1 => 'Can Chown',
2 => 'Can Delete',
3 => 'Can Modify',
4 => 'Can Read',
5 => 'Id',
6 => 'Total Type',
7 => 'Type',
8 => 'Type',
)
I've been playing around with Mongo for about a week now and I still can't work out how to modify nested arrays in Mongo with php.
So here is a sample document...
array (
'_id' => new MongoId("4cb30f560107ae9813000000"),
'email' => 'mo#maurice-campobasso.com',
'firstname' => 'Maurice',
'lastname' => 'Campobasso',
'password' => 'GOD',
'productions' =>
array (
0 =>
array (
'title' => 'a',
'date' => '1286811330.899',
),
1 =>
array (
'title' => 'b',
'date' => '1286811341.183',
),
2 =>
array (
'title' => 'c',
'date' => '1286811350.267',
),
3 =>
array (
'title' => 'd',
'date' => '1286811356.05',
),
),
)
What I wan't to do is delete an array inside the productions array, but I can't work out how. I've been playing with 'update('$pull' => ...etc)' but I haven't been able to make it work.
OK, there are a few ways to do this. In your case, I would do something like
mymongoobject.update( $unset : { "productions.2" : 1 } }
That's basically saying to unset the ".2" element of productions. Some docs here.
Now $pull should also work, but it's a little tougher because "productions" is actually an array of arrays (or objects with sub-objects). So you'd have to match arrays exactly:
mymongoobject.update( $pull : { "productions" : {'title':'d', 'date':'1286811356.05'} }
In the case above, the unset is probably the easiest option (though it will leave a "hole" in the array)
That is actually very easy, unlike traditional sql stuff you just modify the whole data and pass it back.
$cursor = $mongo->yourDB->yourCollection->findOne("_id",4cb30f560107ae9813000000);
//let's remove last item on productions
array_splice($cursor["productions"],2);
//and update the mongo document
echo $mongo->yourDB->yourCollection->update($cursor);
//it echoes 1 if successful
hope it helps.
I would like to retrieve the first key from this multi-dimensional array.
Array
(
[User] => Array
(
[id] => 2
[firstname] => first
[lastname] => last
[phone] => 123-1456
[email] =>
[website] =>
[group_id] => 1
[company_id] => 1
)
)
This array is stored in $this->data.
Right now I am using key($this->data) which retrieves 'User' as it should but this doesn't feel like the correct way to reach the result.
Are there any other ways to retrieve this result?
Thanks
There are other ways of doing it but nothing as quick and as short as using key(). Every other usage is for getting all keys. For example, all of these will return the first key in an array:
$keys=array_keys($this->data);
echo $keys[0]; //prints first key
foreach ($this->data as $key => $value)
{
echo $key;
break;
}
As you can see both are sloppy.
If you want a oneliner, but you want to protect yourself from accidentally getting the wrong key if the iterator is not on the first element, try this:
reset($this->data);
reset():
reset() rewinds array 's internal
pointer to the first element and
returns the value of the first array
element.
But what you're doing looks fine to me. There is a function that does exactly what you want in one line; what else could you want?
Use this (PHP 5.5+):
echo reset(array_column($this->data, 'id'));
I had a similar problem to solve and was pleased to find this post. However, the solutions provided only works for 2 levels and do not work for a multi-dimensional array with any number of levels. I needed a solution that could work for an array with any dimension and could find the first keys of each level.
After a bit of work I found a solution that may be useful to someone else and therefore I included my solution as part of this post.
Here is a sample start array:
$myArray = array(
'referrer' => array(
'week' => array(
'201901' => array(
'Internal' => array(
'page' => array(
'number' => 201,
'visits' => 5
)
),
'External' => array(
'page' => array(
'number' => 121,
'visits' => 1
)
),
),
'201902' => array(
'Social' => array(
'page' => array(
'number' => 921,
'visits' => 100
)
),
'External' => array(
'page' => array(
'number' => 88,
'visits' => 4
)
),
)
)
)
);
As this function needs to display all the fist keys whatever the dimension of the array, this suggested a recursive function and my function looks like this:
function getFirstKeys($arr){
$keys = '';
reset($arr);
$key = key($arr);
$arr1 = $arr[$key];
if (is_array($arr1)){
$keys .= $key . '|'. getFirstKeys($arr1);
} else {
$keys = $key;
}
return $keys;
}
When the function is called using the code:
$xx = getFirstKeys($myArray);
echo '<h4>Get First Keys</h4>';
echo '<li>The keys are: '.$xx.'</li>';
the output is:
Get First Keys
The keys are: referrer|week|201901|Internal|page|number
I hope this saves someone a bit of time should they encounter a similar problem.