Sorting Multi-Dimensional Array PHP - 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 ;)

Related

Assign values in array based on array keys

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;
}

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);

Appending an array to a multi dimensional array fails silently PHP?

I am trying to append an array to another one in a multi dimensional array:
This is the multi dimensional array:
$info[] = array(
'key' => $row['id'],
'master' => array(
'name' => $row['master_name'],
"detail" => array()
)
);
I has a key which is the master id, and a master item which is an array with a name and another array with the detail (at the first time is empty).
But when I try to add to the $info['master']['detail'] array another array with a detail, like this:
$info['master']['detail'][] = array("name" => "A detail name",
"value" => "A detail value");
Nothing is added... How is that possible?
EDIT: the foreach loops that should add the details to the master:
foreach ($details as $detail)
{
$name = $detail['detail_name'];
$value = $detail['detail_value'];
if ($info['key'] == $detail['id']) {
$info['master']['detail'][] = array("name" => $name,
"value" => $value);
}
}
I'm not sure I understand but when I see your examples, I think it is a problem of index:
Try to replace
$info[] = array(
'key' => $row['id'],
'master' => array(
'name' => $row['master_name'],
"detail" => array()
)
);
$info['master']['detail'][] = array("name" => "A detail name",
"value" => "A detail value");
by
$info = array( 'key' => $row['id'],
'master' => array('name' => $row['master_name'],,
"detail" => array())
);
$info['master']['detail'] = array("name" => "A detail name",
"value" => "A detail value");
and to add a new value :
$info['master']['detail']['foo'] = "A detail foo";

Switch between array entries

I am writing an application which interfaces with an external API. We have five API clients (in order to process more requests - which is allowed under the API T&C) which are stored in an array. We have another array of objects which we perform an action on using foreach.
For example:
$clients = array(
array(
"key" => "somekey",
"secret" => "somesecret"
),
array(
"key" => "somekey",
"secret" => "somesecret"
),
array(
"key" => "somekey",
"secret" => "somesecret"
)
);
Next we have an array of objects to be processed:
$objects = array(
array(
"info" => "someinfo",
"url" => "someurl",
"id" => 1234,
"more" => "more"
),
array(
"info" => "someinfo",
"url" => "someurl",
"id" => 1234,
"more" => "more"
),
array(
"info" => "someinfo",
"url" => "someurl",
"id" => 1234,
"more" => "more"
)
);
So to process them with one API key we would do something like:
foreach($objects as $object){
$class->setAPIKey($clients[0]);
$result = $class->process($object);
}
In order to process them with multiple keys we have tried this:
$key = 0;
foreach($objects as $object){
$class->setAPIKey($clients[$key]);
$result = $class->process($object);
if($key + 1 == sizeof($clients)){
$key = 0;
} else {
$key++;
}
}
This works, but seems a little inefficient. Is there a quicker/smaller way to do the same thing?
You can try it like this:
foreach($objects as $key => $object){
$class->setAPIKey($clients[$key]);
$result = $class->process($object);
}

Categories