PHP: Getting values by date [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Im new In PHP!.
I have an array that contains dates and vlaues. How do i get all values of
specific date?. EXp: I would like to get all values from year 2015. If someone Knows can guide me.

You could use array_filter, then check the array key substr matches the date.
<?php
$date = 2016;
$array = [
'2016-01-01' => 'a',
'2016-01-02' => 'b',
'2016-12-01' => 'c',
'2017-01-04' => 'd',
'2017-01-05' => 'e',
'2017-01-06' => 'f',
];
$result = array_filter($array, function ($key) use ($date) {
return substr($key, 0, strlen($date)) == $date;
}, ARRAY_FILTER_USE_KEY);
print_r($result);
https://3v4l.org/UYaQq
Result:
Array
(
[2016-01-01] => a
[2016-01-02] => b
[2016-12-01] => c
)

<?php
$array = array('2015-01-01' => "test1",
'2013-02-04' => "test2",
'2011-03-08' => "test3",
'2016-03-08' => "test3");
foreach( $array as $key => $value ){
if(date('Y',strtotime($key)) >= 2015)
echo $value . ", ";
}
?>

An Array Contains a Key and a Value. The Key in your case is the Date. And the Value is... the value
You define it like this
$array = array(
Date => Value,
AnotherDate => AnotherValue,
);
or since PHP5
$array = [
Date => Value,
AnotherDate => AnotherValue,
];
if you now look at your Array using
var_dump($array);
You'll see the date is already combined with your value and It will even show the type of value (boolean, string, integer...)
Edit
Anotherone was faster

Related

PHP: can't add to empty associative array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
i'm missing something simple here trying to add a new key/value pair and then add to the value of that pair as this loop goes on. this throws an undefined index error:
$someAssocArray = [2] => 'flarn'
[3] => 'turlb'
$someOtherAssocArray = [0] => 'id' => '11'
'name' => 'flarn'
[1] => 'id' => '22'
'name' => 'turlb'
[2] => 'id' => '33'
'name' => 'turlb'
[3] => 'id' => '44'
'name' => 'flarn'
$idList = [];
foreach($someAssocArray as $key=>$value) {
foreach($someOtherAssocArray as $item) {
if($item['name'] === $value) {
$idList[$value] += $item['id'];
}
}
}
the end result of idList should look like this:
$idList = [ "flarn" => "11,44"
"turlb" => "22,33" ]
so please tell me what i'm missing so i can facepalm and move on.
[Edit] OK I just re-read that question and I might be misunderstanding. Is the desired output of 11,44 supposed to represent the sum of the values? Or a list of them?
This code will generate a warning if $idList[$value] doesn't exist:
$idList[$value] += $item['id'];
This is happening because it has no value yet for the first time you're incrementing. You can avoid this issue by initializing the value to zero for that first time when it doesn't exist:
If you want a sum of the values:
if($item['name'] === $value) {
$idList[$value] ??= 0; // initialize to zero
$idList[$value] += $item['id']; // add each value to the previous
}
If you want a list of the values:
if($item['name'] === $value) {
$idList[$value] ??= []; // initialize to an empty array
$idList[$value][] = $item['id']; // append each element to the list
}
(Then you can use implode() to output a comma-separated string if desired.)

Transpose data in an associative array of indexed arrays [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 6 months ago.
I'm not sure how to search for the problem I'm facing, so that's why I'm asking here.
I want to know if there is a native php-function to transform following array I get from a html-form:
Original Array
$array = [
'product_template_id' => [
'0' => '1',
'1' => '2'
],
'amount' => [
'0' => '50',
'1' => '100'
]
]
Desired Array
$array = [
'0' => [
'product_template_id' => '1',
'amount' => '50'
],
'1' => [
'product_template_id' => '2',
'amount' => '100'
]
]
I know this can be done with a loop, but that's not what I'm asking for.
PS(not my main question, just a sidequestion): How can I bulk format code in stackoverflow? Is it always 4 spaces? How can I perform the formatting quicker?
edit: PS is not the main question, it is more of a sidenote which has already been answered by #RiggsFolly
Just as prove of concept you can use array_map:
$keys = array_keys($array);
// For < PHPv5.6
// $zip = call_user_func_array('array_map', array_merge([null], $array));
$zip = array_map(null, ...array_values($array));
$result = array_map(function ($item) use ($keys) {
return array_combine($keys, $item);
}, $zip);
Here is working demo.
But in practice, there is too much overhead for so simple problem.
EDIT:
Here I am zipping (getting one corresponding element from each array and creating an array of this elements) all child arrays. It is done with array_map using its property:
An interesting use of this function is to construct an array of arrays, which can be easily performed by using NULL as the name of the callback function
As array_map can take an arbitrary number of arrays, I supply them to it with '...' splat operator.
This does what you need!
for ($x = 0; $x < count($array['amount']); $x ++) {
$arr[$x] = [
'product_template_id' => $array['product_template_id'][$x],
'amount' => $array['amount'][$x],
];
}
See here for a working example https://3v4l.org/dokHK

Removing unwanted key/value pair in php array? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
$data = array("0"=>"1","id"=>"1","1"=>"mani","name"=>"mani","2"=>"ssss","lname"=>"ssss");
above is my output but i want an array like below format. Please help me.
Correct Output:
$data = array ("id"=>"1","name"=>"mani","lname"=>"ssss");
check this, use is is_numeric to check number or string.
$data = array("0"=>"1","id"=>"1","1"=>"mani","name"=>"mani","2"=>"ssss","lname"=>"ssss");
foreach ($data as $key => $val)
{
if(!is_numeric($key))
{
$new_array[$key] = $val;
}
}
print_r($new_array);
OUTPUT :
Array
(
[id] => 1
[name] => mani
[lname] => ssss
)
DEMO
The Code-Snippet below contains Self-Explanatory Comments. It might be of help:
<?php
// SEEMS LIKE YOU WANT TO REMOVE ITEMS WITH NUMERIC INDEXES...
$data = array( "0" => "1",
"id" => "1",
"1" => "mani",
"name" => "mani",
"2" => "ssss",
"lname"=> "ssss"
);
// SO WE CREATE 2 VARIABLES TO HOLD THE RANGE OF INTEGERS
// TO BE USED TO GENERATE A RANGE OF ARRAY OF NUMBERS
$startNum = 0; //<== START-NUMBER FOR OUR RANGE FUNCTION
$endNum = 10; //<== END-NUMBER FOR OUR RANGE FUNCTION
// GENERATE THE RANGE AND ASSIGN IT TO A VARIABLE
$arrNum = range($startNum, $endNum);
// CREATE A NEW ARRAY TO HOLD THE WANTED ARRAY ITEMS
$newData = array();
// LOOP THROUGH THE ARRAY... CHECK WITH EACH ITERATION
// IF THE KEY IS NUMERIC... (COMPARING IT WITH OUR RANGE-GENERATED ARRAY)
foreach($data as $key=>$value){
if(!array_key_exists($key, $arrNum)){
// IF THE KEY IS NOT SOMEHOW PSEUDO-NUMERIC,
// PUSH IT TO THE ARRAY OF WANTED ITEMS... $newData
$newData[$key] = $value;
}
}
// TRY DUMPING THE NEWLY CREATED ARRAY:
var_dump($newData);
// YIELDS::
array (size=3)
'id' => string '1' (length=1)
'name' => string 'mani' (length=4)
'lname' => string 'ssss' (length=4)
Or even concisely, you may walk the Array like so:
<?php
$data = array(
"0" => "1",
"id" => "1",
"1" => "mani",
"name" => "mani",
"2" => "ssss",
"lname" => "ssss"
);
array_walk($data, function($value, $index) use(&$data) {
if(is_numeric($index)){
unset($data[$index]);
}
});
var_dump($data);
// YIELDS::
array (size=3)
'id' => string '1' (length=1)
'name' => string 'mani' (length=4)
'lname' => string 'ssss' (length=4)
$data = array("0"=>"1","id"=>"1","1"=>"mani","name"=>"mani","2"=>"ssss","lname"=>"ssss");
$new_data = array();
foreach($data as $k => $v)
if(strlen($k)>1) $new_data[$k] = $v;
print_r($new_data);
I'm a little confused as to what exactly you're looking for. You give examples of output, but they look like code. If you want your output to look like code you're going to need to be clearer.
Looking at tutorials and documentation will do you alot of good in the long run. PHP.net is a great resource and the array documentation should help you out alot with this: http://php.net/manual/en/function.array.php

Optimized code for only max value in array in php [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
hi there I designed a blog page....per page 10 artilcs!
I want return biggest time (stamptime) for each 10 articls (like publish up time,publish down time,created,modifed time) to create meta tag.
so I have a list of 10 artiles (each article is an array with all parameters like date,content,title,...) that I saved them in $list array.
like this:
$list = array ( array('id' => '1', 'modifed ' => '123123123' ...
I want return biggest value...the articls are mixed.
I use this code:
$data['created'] = array_reduce($list, function ($a, $b) {
return #$a['created'] > $b['created'] ? $a : $b ;
$data['modified'] = array_reduce($list, function ($a, $b) {
return #$a['modified'] > $b['modified'] ? $a : $b ;
$data['publish_up'] = array_reduce($list, function ($a, $b) {
return #$a['publish_up'] > $b['publish_up'] ? $a : $b ;
$data['publish_down'] = array_reduce($list, function ($a, $b) {
return #$a['publish_down'] > $b['publish_down'] ? $a : $b ;
My only worry is it maybe has a bad effect in my loading page.
do you think this code is Optimized?
Here's my solution. But as Sven said, you need to be more specific.
//fake data
$data = array(
array('id' => 1, 'upd' => 111, 'created' => 333),
array('id' => 2, 'upd' => 1203, 'created' => 43),
array('id' => 3, 'upd' => 144, 'created' => 533),
);
// here, I'm first computing the max of each column
// I place the results in an array and returns ultimately the max
echo max(
array(
max(array_column($data, 'upd')),
max(array_column($data, 'created'))
)
);
// here, it returns 1203, as there is an element "upd" with value 1203
If you do not have php 5.5, you have the following options:
use a php implementation that matches the behaviour of php 5.5 : https://github.com/ramsey/array_column/blob/master/src/array_column.php
upgrade to php 5.5 ;)
implements the function with map
The option 3 leads to the following code:
echo max(
array(
max(array_map(function($arr){return $arr['upd'];}, $data)),
max(array_map(function($arr){return $arr['created'];}, $data)),
)
);

How to define a custom key in PHP arrays? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to define a two dimension array like below:
[40.1][John]
[40.2][Jane]
[40.7][Mary]
[40.10][Sara]
in other words I want to define an array with custom key. Later I need to access to the array values with the custom key. for instance :
echo(myarray[40.2]);
And I need to generate the array dynamically from XML , since the values are coming from a XML file.
The XML file which I want to generate the array from is like below:
<rules>
<rule>
<id>40.1</id>
<regex><![CDATA[/(?:\)\s*when\s*\d+\s*then)/]]></regex>
</rule>
<rule>
<id>40.2</id>
<regex><![CDATA[/(?:"\s*(?:#|--|{))/]]></regex>
</rule>
How should I create the array with above characteristics?
You can do this very easily by creating an associative array
$myarray = array(
"40.1" => "John",
"40.2" => "Jane",
"40.7" => "Mary",
"40.10" => "Sara"
);
Later on you can iterate over this array with a foreach loop
foreach($myarray as $key => $value) {
echo "<p>" . $key . " = " . $value . "</p>";
}
This will output to the screen
40.1 = John
40.2 = Jane
40.7 = Mary
40.10 = Sara
To create a new array and add items to is as easy as doing this
$myarray = array();
$myarray[$newkey] = $newvalue;
For a two dimensional array, you can define them like this
$myarray = array();
$myarray[$key] = array();
$myarray[$key]['John'] = 'some value';
$myarray[$key]['Jane'] = 'another value';
$myarray[$key2] = array();
$myarray[$key2]['Mary']= 'yet another value';
Or as a short cut
$myarray = array(
$key => array(
'John' => 'some value',
'Jane' => 'another value',
),
$key2 = array(
'Mary' => 'yet another value'
)
);
You can do it with associative array key => value.
$arr = array('40.1' => 'John', '40.2' => 'Jane', '40.7' => 'Mary', ...);
echo $arr['40.1']; // will return John
If you think to extend the data in the feature, you can do it with nested arrays
$arr = array(
'40.1' => array('name' => 'John', 'eyes' => 'green');
'40.2' => array('name' => 'Jane', 'eyes' => 'blue');
);
You can access nested array like this:
echo $arr['40.2']['eyes'] // return blue
You can see also PHP documentation about arrays here
Array keys
Notice! Do not use "float" as type for array keys.
<?php
$array = array(
1 => "a",
"1" => "b",
1.5 => "c",
true => "d",
);
var_dump($array);
Output will be:
array(1) {
[1]=>
string(1) "d"
}
Taken from http://www.php.net/manual/en/language.types.array.php.
Two-dimensional arrays
You can create your array like this:
$data = [
'40.2' => [
'John' => [
// and now this is second dimension
]
]
];
Add aditional stuff:
$data['40.2']['John'][] = ; // just append value
// or
$data['40.2']['John']['sex'] = 'Male'; // store it with key
Or if you need to store scalar values, you can define array like this:
$data = [
'40.2' => [
'John' => 'male' // storing scalar values
]
];
Sorry, If I misunderstood your question.

Categories