PHP array to an Array of Objects [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 7 years ago.
Improve this question
how would I convert my array to an array of objects with PHP ?
input
[1, 2, 3]
output
[ {id:1}, {id:2}, {id:3} ]

When you have to reformat array, e.g. transorm values of the array to another format (number to object with id->number) and they map 1:1 (the new array have the same number of elements like the original), array_map is the solution
$newArray = array_map(function($item) {
$object = new \StdClass;
$object->id = $item;
return $object;
}, $array);

If you defined your object before, I guess I'd do a loop
class previouslyDefinedObject{
public $id;
}
$myArray = array(1,2,3);
$newArray = array();
foreach($myArray as $id){
$obj = new previouslyDefinedObject();
$obj->id = $id;
array_push($newArray, $obj);
}
print_r($newArray);
That way, your $newArray will contains every object in an array

Related

how to merge data array of to array in php [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 months ago.
Improve this question
how to merge data array of to array in php?
i have 2 arrays like:
$a=[1,2]; $b =[3,4];
and i want to merge data like:
$data = [[1,3]],[2,4]];
how to code in php like array_merge or something in php or laravel?
i have try using array_merge but not my expectation data like this:
$data = array_merge($a, $b);
but data always return
[1,2,3,4]
i have clue about this, can someone help this problem?
Since we concluded in the comments that you actually want a multidimensional array, we need to create new arrays so we can swap the values around between the original arrays.
Here's one possible solution (the comments explain the different parts)
$a = [1,2];
$b = [3,4];
// Initiate a new array
$newArray = [];
// Iterate through one of the arrays
foreach ($a as $index => $value) {
// On each iteration, take the values from both arrays for that specific array index
// and add them as a new sub array.
$newArray[] = [
$a[$index],
$b[$index]
];
}
$newArray will now contain a multidimensional array:
[[1,3],[2,4]]
Here's a demo: https://3v4l.org/okHhQ

How to sort an array with name, date and quantity? 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 2 years ago.
Improve this question
I have this array and I would like to sort the dates for the graphs.[]
1
Before I was using this function because I was only bringing in the array example ````$data[$date] = $total``` but now I am bringing in the name, date and total.
foreach ($_data_ as $key => $value) {
$_date[] = $value->fecha;
$_dataOpportunities[$value->name][$value->fecha] = $value->total;
}
foreach ($_dataOpportunities as $key => $value) {
for ($i=0; $i < count($_date) ; $i++) {
if (!array_key_exists($_date[$i],$value)) {
$_dataOpportunities[$key][$_date[$i]] = 0;
}
}
}
//Order by date //Not order
foreach ($_dataOpportunities as $key => $value) {
//dd($value);
uksort($value,['self','compare_date_keys']);
}
dd($_dataOpportunities);
public static function compare_date_keys($dt1, $dt2) {
return strtotime($dt1) - strtotime($dt2);
}
The dd($value) returns this:
And when it exits the foreach and returns the variable dd($_dataOpportunities); it returns me the following:
Dates are still not sorted.
I tried uksort and usort and still the date order does not work.
Assuming the multi-dimensional array is $array:
function key_cmp_date($dt1, $dt2) {
return strtotime($dt1) - strtotime($dt2);
}
foreach($array as $key=>$val){
uksort($array[$key],"key_cmp_date");
}
I haven't tested it, but this should suffice.
Try using ksort($arr) function to sort the array. I haven't tried this, but I think this will work.

Laravel Helper to merge Period arrays [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Laravel Version:7.0
I would like to know how to create this helper.
Input is date range array. For example:
$input1 = [2020-07-19, 2020-07-25];
$input2 = [2020-07-26, 2020-08-01];
$input3 = [2020-08-01, 2020-08-07];
$input4 = [2020-10-01, 2020-10-07];
$input5 = [2020-10-19, 2020-10-25];
I would like to make one helper function.
function mergeDate($array)
{
...
}
So when I use this helper, I would like to get as following result.
$array = [$input1, $input2, $input3, $input4, $input5];
$mergedResult = mergeDate($array);
$mergedResult[0] = [2020-07-19, 2020-08-07];
$mergedResult[1] = [2020-10-01, 2020-10-07];
$mergedResult[2] = [2020-10-19, 2020-10-25];
Can anyone help me how to make mergeDate function?
Input period elements aren't overlapped.
Thank you!
This would be my first guess at how to solve it.
public function merge($array){
$results = [];
foreach ($array as $element){
if (sizeof($results) == 0){
array_push($results,$element);
}else{
$found = null;
foreach ($results as $key => $r){
if (Carbon::parse($element[0])->equalTo(Carbon::parse($r[1])))
{
$found = $key;
break;
}
}
if (!is_null($found)){
$results[$found][1] = $element[1];
}else{
array_push($results, $element);
}
}
}
return $results;
}
It is a simple take on the problem. If our resulting array is empty we add the first element otherwise we iterate over the results to find a matching pair of the elements end date and the start date of the item in the results array. If we find a matching start end pair we replace the results end value with the elements end value. Otherwise we have no overlap and we can add it as a new item to the results array.
An interesting library to use would be the Spatie/Period library.
https://github.com/spatie/period
#edit
since the array is not sorted as mentioned in a comment above, you would have to sort it prior.

How to create new assoc array using two other assoc arrays in PHP? [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 5 years ago.
Improve this question
I have two associative arrays:
$array1=[key1=>$value1,key2=>$value2,key3=>$value3];
$array2=[key1=>$value1,key2=>$value2,key4=>$value4];
How to create the following array:
$arraytotal=[key1=>$value1,key2=>$value2,key3=>$value3,key1=>$value1,key2=>$value2,key4=>$value4];
array_merge is not an option because i have to keep the same values in the final array.
Tnx.
You can't have multiple keys set to the same value (you have key1 in each array), and as you've seen, the second key1 will override the first when you use array_merge.
Your options depend on if each original array functions as a separate group of key/value pairs, or if you want similar key/value pairs grouped together.
So, the first one is easy:
$array1=[key1=>$value1,key2=>$value2,key3=>$value3];
$array2=[key1=>$value1,key2=>$value2,key4=>$value4];
$super = [$array1, $array2];
The second needs a bit more looping:
$array1=[key1=>$value1,key2=>$value2,key3=>$value3];
$array2=[key1=>$value1,key2=>$value2,key4=>$value4];
$super = [];
foreach ($array1 as $key => $value) {
$super[$key] = [$value];
}
foreach ($array2 as $key => $value) {
if (!isset($super[$key])) {
$super[$key] = [];
}
$super[$key][] = $value;
}
If you know that you'll always have the same keys in each array, then you can skip the isset

Confused about this php code [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 8 years ago.
Improve this question
foreach($items as $value)
{
if($value['item1']=='somestring')
{
// some PHP code...
}
}
Shouldn't $value refer to each value in $items array. What do they mean by $value['item1']? Does it mean $items is a multidimensional array or something?
It means $value is an array and therefore $items is a multidimensional array.
The $foo[] syntax is used by arrays and objects that emulate them (if that's what you mean). The index can be an integer or a string. As you already point out, PHP allows multidimensional arrays.
If you print $key and $value then out show you good result
foreach($items as $key=>$value) // $items contain array mean multidimensional
{
print_r($value);
print($key);//$key is index value
//item1 is array element and $value is array exist in $items
if($value['item1']=='somestring')
{
some PHP code...
}
}
so $items multidimensional array and $value array exist in $items array that's by $items multidimensional array
It means that $items is a multi-dimensional array.
And its looped over.
It has following structure for example:
array(
0 => array('item1' => 'something'),
1 => array('item1' => 'something1')
);
Through this code, we are looping so, in the statement,
foreach($items as $value)
We are getting the inner arrays 0, 1, .. and so on.
And in the line, if($value['item1']=='somestring'), we are getting array elements of 0, 1, and so on.
Hope you understand.
'item1' is the key to one of the elements inside the array $value.
So yes, this makes $items a multidimensional array.
All above are true if no errors are found running the code.

Categories