Assign values in array based on array keys - php

How to modify an array based on the value as key?
array(
array(
"name" => "BIBAR",
"cutoff" => 20220725,
"totals" => 5614
),
array(
"name" => "BIBAR",
"cutoff" => 20220810,
"totals" => 5614
),
array(
"name" => "BIBAR",
"cutoff" => 20220825,
"totals" => 5614
)
);
I tried the following but it's not working:
foreach($cutoffs as $catoff) {
$ii = 0;
$sums[$ii][$catoff] = array_filter($array, function($val){
return $val['cutoff'] === $catoff ? $val['totals'] : $val;
});
$ii++;
}
My desired array:
array(
'20221025' => array(
12345,
12343,
24442
),
'20221110' => array(
3443,
744334
)
)
I'm stuck here for hours ... Please help

IF the "name" is irrelevant, I think also the previous answer should be fine.
If this code does "not work", then your explanation might be wrong, so you need to either explain better, or give us more examples - please mind that in your example the input and output are very different - the input you gave does not match your ouput.
My code is:
$a = array(
array(
"name" => "BIBAR",
"cutoff" => 20220725,
"totals" => 5614
),
array(
"name" => "BIBAR",
"cutoff" => 20220810,
"totals" => 5614
),
array(
"name" => "BIBAR",
"cutoff" => 20220725,
"totals" => 1234
)
);
print_r($a);
echo "\n================================\n\n";
$newArr = [];
foreach ($a as $k => $vArr) {
// maybe some validation would be useful here, check if they keys exist
$newArr[$vArr['cutoff']][] = $vArr['totals'];
}
print_r($newArr);

function changeArr($data){
$new = [];
foreach ($data as $v){
$new[$v['cutoff']][] = $v['totals'];
}
return $new;
}

Related

Extracting from mulit-array and putting it into my own - php

I'm trying to extract data from a multidimensional array and then putting into one of my own so that I can load it into my database.
Source:
array( "ListOrdersResult" =>
array ( "Orders" =>
array( "Order" =>
array( [0] => {
"Title" => $productTitle,
"customer_name" => $customerName,
"customer_id" => $customerId,
"random_info" => $randomInfo
},
[1] => {
"Title" => $productTitle,
"customer_name" => $customerName,
"customer_id" => $customerId,
"random_info" => $randomInfo
}
)
)
)
To do this, I'm cycling through it like this - I have no issues with extracting data.
My code:
$count = count($listOrderArray['ListOrdersResult']['Orders']['Order']);
//Cycle through each Order to extract the data I want
for($i = 0; $count > $i; $i++) {
$baseArray = $listOrderArray['ListOrdersResult']['Orders']['Order'][$i];
foreach($baseArray as $key => $value) {
if($key == "Title" || $key == "customer_id") {
//ADD TO multidimensional array
}
}
}
How I'm trying to structure it.
array( [0] => {
array(
"Title" => $title,
"customer_id" => $customer_id
},
[1] => {
"Title" => $nextTitle,
"customer_id" => $next_customer_id
}
);
The ultimate goal is to make it easier to load the information into the database by gathering the data by record and then loading it to the database rather than loading by creating an new record and then coming back and modifying that record. To me that seems like it would take more resources and has a higher chance of inconsistent data, but I'm new so I could be wrong.
Any help would be greatly appreciated.
You only have to unset keys you don't want:
$result = array_map(function ($i) {
unset($i['customer_name'], $i['random_info']);
return $i;
}, $listOrderArray['ListOrdersResult']['Orders']['Order']);
More about array_map
Or you also can select the keys you want:
$result = array_map(function ($i) {
return ['Title' => $i['Title'], 'customer_id' => $i['customer_id']];
}, $listOrderArray['ListOrdersResult']['Orders']['Order']);
About your code and question:
$count = count($listOrderArray['ListOrdersResult']['Orders']['Order']);
//Cycle through each Order to extract the data I want
for($i = 0; $count > $i; $i++) {
There's no reason to use a count and a for loop, use foreach.
array( [0] => {
array(
"Title" => $title,
"customer_id" => $customer_id
},
[1] => {
"Title" => $nextTitle,
"customer_id" => $next_customer_id
}
);
doesn't make sense, what are these curly brackets? You should write it like this if you want to be understood:
array(
[0] => array(
"Title" => "fakeTitle0",
"customer_id" => "fakeCustomerId0"
),
[1] => array(
"Title" => "fakeTitle1",
"customer_id" => "fakeCustomerId1"
)
);
You have this initial variable.
$listOrderArray = array(
"ListOrdersResult" => array(
"Orders" => array(
"Order" => array(
0 => array(
"Title" => "productTitle",
"customer_name" => "customerName",
"customer_id" => "customerId",
"random_info" => "randomInfo",
),
1 => array(
"Title" => "productTitle",
"customer_name" => "customerName",
"customer_id" => "customerId",
"random_info" => "randomInfo",
),
)
)
)
);
The only thing you should do is to remove the inner array from the three outer arrays.
Here is the solution:
$orders = $listOrderArray['ListOrdersResult']['Orders']['Order'];

PHP multidimensional array search key by value

For example a multidimensional array like an example below
$arr = array(
[H1] => array(
"name" => "A"
"title" => "T1"
)
[H2] => array(
"name" => "B"
"title" => "B1"
)
)
Let's say I would like to search name which equals to A in $arr and if it's matched, the searching should return the key which is H1
How can I do that in php ?
I tried array_keys($arr, "A") but it returns me with an array instead of the key.
This may help -
$arr = array(
'H1' => array(
"name" => "A",
"title" => "T1",
),
'H2' => array(
"name" => "B",
"title" => "B1",
)
);
// Generate a new array with 'keys' and values in 'name'
$new = array_combine(array_keys($arr), array_column($arr, 'name'));
// Search in that new array
$search = array_search('A', $new);
var_dump($search);
Output
string(2) "H1"
Demo
Another simple way would be -
$serach= false;
foreach($arr as $key => $val) {
if($val['name'] == 'A') {
$search= $key;
break;
}
}
var_dump($search);

Sorting Multi-Dimensional Array PHP

I've that proceed this array in PHP
array(
"id" => 1,
"name" => "Carlos"
"other" => array("key" => "Hello")
),
array(
"id" => 3,
"name" => "Carlos"
"other" => array("key" => "Hello")
),
array(
"id" => 2,
"name" => "Carlos"
"other" => array("key" => "Hello")
)
and I need to order by "id". I've try it using usort and many multidimensional solutions but doesn't work for me.
I used that:
$price = array();
foreach ($inventory as $key => $row)
{
$price[$key] = $row['price'];
}
array_multisort($price, SORT_DESC, $inventory);
But doesn't work because my array has many dimentions.
$departamento = $this->Departamentos->get($id, [
'contain' => [
'Asignaturas.Mallas',
'Asignaturas.Secciones.Perfiles',
'Asignaturas.Secciones.Mallas.Carreras',
'Unidades'
]
]);
That is my query in Cakephp. I need to order by Secciones.id
I used Hash::sort
http://book.cakephp.org/3.0/en/core-libraries/hash.html
And works fine for me ;)

Put array elements with specific value to end of array

I have a multidimensional array like that:
$array = array(
1 => array(
"name" => 'Jon',
"year" => '2012'
),
2 => array(
"name" => 'Jack',
"year" => '1900'
),
3 => array(
"name" => 'Lisa',
"year" => '1900'
),
4 => array(
"name" => 'Ygritte',
"year" => '1929'
),
);
All the items that have a year of '1900' should be put to the end of the array. What is a lightweight solution?
Desired result:
$array = array(
1 => array(
"name" => 'Jon',
"year" => '2012'
),
2 => array(
"name" => 'Ygritte',
"year" => '1929'
),
3 => array(
"name" => 'Jack',
"year" => '1900'
),
4 => array(
"name" => 'Lisa',
"year" => '1900'
),
);
I assume you don't care about your indexes because you rearrange them. First thing, you should probably start indexes in your array from 0 and not for 1.
You can use the following code:
$array = array(
1 => array(
"name" => 'Jon',
"year" => '2012'
),
2 => array(
"name" => 'Jack',
"year" => '1900'
),
3 => array(
"name" => 'Lisa',
"year" => '1900'
),
4 => array(
"name" => 'Ygritte',
"year" => '1929'
),
);
$array = array_values($array);
for ($i=0, $c = count($array); $i<$c; ++$i) {
if ($array[$i]['year'] == '1900') {
$array[] = $array[$i];
unset($array[$i]);
}
}
$array = array_values($array);
foreach ($array as $k => $v) {
echo $k.' '.$v['name'].' '.$v['year']."<br />";
}
Result for this is:
0 Jon 2012
1 Ygritte 1929
2 Jack 1900
3 Lisa 1900
Of course if you want, you can change your keys adding 1 to each one (starting from the last element) so you have the same output as in question but I assume this one is enough for you.
The simplest approach could be something like this:
Find the element that has year 1900 (iterating the loop) then,
For example working for index 3
$tmp = $myArray['3'];
unset($myArray['3'];
$myArray['3'] = $tmp;
$tmp is a temporary variable inside the loop.
Try using SplHeap
class MyQueue extends SplHeap
{
public function compare($item1, $item2)
{
if ($item1['year'] === $item2['year']) return 0;
return ($item1['year'] == 1900) ? -1 : 0;
}
}
$queue = new MyQueue();
foreach ($array as $item) {
$queue->insert($item);
}
$queue->top();
$array = array();
while($queue->valid()){
$array[] = $queue->current();
$queue->next();
}
print_r($array);
Hope this following code will help you:
function aasort (&$array, $key) {
$sorter=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
$sorter[$ii]=$va[$key];
}
rsort($sorter);
foreach ($sorter as $ii => $va) {
$ret[$ii]=$array[$ii];
}
$array=$ret;
}
aasort($array,"year");
print_r($array);

Not getting array all values using php

I have this following array
$question = array(
"ques_15" => array(
"name" => array(
"0" => "aaa"
)
),
"ques_16" => array(
"name" => array(
"0" => "bbb",
"1" => "ccc"
)
)
);
$i=0;
foreach($question as $k=>$v)
{
echo $question[$k]['name'][$i];
$i++;
}
But my output is only
aaaccc
I am missing the value bbb
You need to iterate the inner 'name' arrays - you could use a nested foreach loop:
$question = array(
"ques_15" => array(
"name" => array(
"0" => "aaa"
)
),
"ques_16" => array(
"name" => array(
"0" => "bbb",
"1" => "ccc"
)
)
);
foreach($question as $quest)
{
foreach($quest['name'] as $val)
{
echo $val;
}
}
you should loop though like so
foreach($question as $q)
{
foreach($q['name'] as $v)
{
echo $v;
}
}
in foreach you don't need a counter $i, it's for while() or for()
you array is two dimensional so you need 2 foreach
Check it out in a functional way.
The shorthand array declaration works only on PHP 5.4+ though, but it still works with your longhand array declaration.
$questions = [
'ques_15' => ['name' => ['aaa']],
'ques_16' => ['name' => ['bbb', 'ccc']]
];
array_map(function($a){
foreach ($a['name'] as $v) echo $v;
}, $questions);

Categories