I am trying to add my data to my array inside my foreach loop.
I have almost done it successfully, except the array is too in-depth.
It's showing array->array->{WHAT I WANT}
When I need array->{WHAT I WANT}
Example, I'm needing it to be like:
Array
(
[home] => Array
(
[0] => Dashboard\Main#index
[1] => GET
)
[home/] => Array
(
[0] => Dashboard\Main#index
[1] => GET
)
)
When at the moment, it's showing:
Array
(
[0] => Array
(
[services/content-writing] => Array
(
[0] => Dashboard\Services#contentwriting
[1] => GET
)
)
[1] => Array
(
[services/pbn-links] => Array
(
[0] => Dashboard\Services#pbnlinks
[1] => GET
)
)
)
The code I'm currently using inside my foreach loop is:
$realArray = array();
// Services exist
if($services)
{
// Sort them into our array
foreach ($services as $service) {
$servicePageName = $service->page_name;
$serviceName = str_replace(' ', '', strtolower($service->name));
$realArrayNew = array(
"services/$servicePageName" => ["Dashboard\Services#$serviceName", 'GET']
);
array_push($realArray, $realArrayNew);
//'home' => ['Dashboard\Main#index', 'GET'],
}
}
return $realArray;
The servicePageName variable must be the key field on the realArray to get the results you want.
I'm presuming you input object array looks something like this:
[
(int) 0 => object(stdClass) {
name => 'contentwriting'
page_name => 'content-writing'
},
(int) 1 => object(stdClass) {
name => 'pbnlinks'
page_name => 'pbn-links'
}
]
If we do this:
$realArray = [];
if ($services) {
foreach ($services as $service) {
$servicePageName = $service->page_name;
$serviceName = str_replace(' ', '', strtolower($service->name));
$realArray["services/$servicePageName"] = [
0 => "Dashboard\Services#$serviceName",
1 => "GET"
];
}
}
This is what we get on realArray:
[
'services/content-writing' => [
(int) 0 => 'Dashboard\Services#contentwriting',
(int) 1 => 'GET'
],
'services/pbn-links' => [
(int) 0 => 'Dashboard\Services#pbnlinks',
(int) 1 => 'GET'
]
]
This portion of the code inserts a new subarray to your main array:
$realArrayNew = array(
"services/$servicePageName" => ["Dashboard\Services#$serviceName", 'GET']
);
array_push($realArray, $realArrayNew);
Replace it all with:
$realArray["services/$servicePageName"] = ["Dashboard\Services#$serviceName", 'GET'];
That way your top level will have service names as keys.
Related
I have an objectlist:
$deliveryOptions =
Array ( [0] => stdClass Object ( [item_id] => 55 [value] => delivery-online )
[1] => stdClass Object ( [item_id] => 55 [value] => delivery-campus )
[2] => stdClass Object ( [item_id] => 56 [value] => delivery-campus )
[3] => stdClass Object ( [item_id] => 81 [value] => delivery-blended )
)
I need to format it to an array:
$combined =
( [item_id] => 55 [course-delivery] => array( "delivery-online","delivery-campus")
( [item_id] => 56 [course-delivery] => delivery-campus )
( [item_id] => 81 [course-delivery] => delivery-blended )
My code so far:
foreach ($deliveryOptions as $row)
{
$temp = array('item_id'=>$row->item_id,
'course-delivery'=>$row->value
);
$course[] = $temp;
}
foreach ($course as $row)
{
$match = array_search($row['item_id'], array_column($combined, 'item_id'));
if(is_numeric($match))
{
$combined[$match]['course-delivery'][] = $row['course-delivery'];
}
else{
array_push($combined, [
'item_id' => $row['item_id'],
'course-delivery' => array($row['course-delivery'])
]);
}
}
The format of $combined might seem odd, but I have three different queries creating different object lists that all need to be combined into one JSON array based on 'item_id' as the key.
I have the part where all three get combined working, this new array configuration comes from a checkbox situation, thus the need to combine the different values off the same item_id.
No need for another foreach, you just create the structure along the way. First, initialize the container for the particular item_id.
When an item_id hits again and is not an array, just overwrite it, use the first value (string) and turn it to an array and finally push the value.
$deliveryOptions = [
(object) ['item_id' => 55, 'value' => 'delivery-online'],
(object) ['item_id' => 55, 'value' => 'delivery-campus'],
(object) ['item_id' => 56, 'value' => 'delivery-campus'],
(object) ['item_id' => 81, 'value' => 'delivery-blended'],
];
$combined = [];
foreach ($deliveryOptions as $row) {
if (!isset($combined[$row->item_id])) { // initialize if it doesn't exist
$combined[$row->item_id] = (array) $row; continue;
}
if (!is_array($combined[$row->item_id]['value'])) { // if another occurence
$temp = $combined[$row->item_id]['value']; // get the string initial value
$combined[$row->item_id]['value'] = []; // turn it into an array
$combined[$row->item_id]['value'][] = $temp; // and reassign and push inside the array
}
$combined[$row->item_id]['value'][] = $row->value; // push the value in the array
}
// $combined = array_values($combined); // array key reindex if needed
Sample output
I have an multidimensional array and I need to count their specific value
Array
(
[0] => Array
(
[Report] => Array
(
[id] => 10
[channel] => 1
)
)
[1] => Array
(
[Report] => Array
(
[id] => 92
[channel] => 0
)
)
[2] => Array
(
[Report] => Array
(
[id] => 18
[channel] => 0
)
)
[n] => Array
)
I need to get output like that: channel_1 = 1; channel_0 = 2 etc
I made a function with foreach:
foreach ($array as $item) {
echo $item['Report']['channel'];
}
and I get: 1 0 0 ... but how can I count it like: channel_1 = 1; channel_0 = 2, channel_n = n etc?
Try this. See comments for step-by-step explanation.
Outputs:
array(2) {
["channel_1"]=>
int(1)
["channel_0"]=>
int(2)
}
Code:
<?php
// Your input array.
$a =
[
[
'Report' =>
[
'id' => 10,
'channel' => 1
]
],
[
'Report' =>
[
'id' => 92,
'channel' => 0
]
],
[
'Report' =>
[
'id' => 18,
'channel' => 0
]
]
];
// Output array will hold channel_N => count pairs
$result = [];
// Loop over all reports
foreach ($a as $report => $values)
{
// Key takes form of channel_ + channel number
$key = "channel_{$values['Report']['channel']}";
if (!isset($result[$key]))
// New? Count 1 item to start.
$result[$key] = 1;
else
// Already seen this, add one to counter.
$result[$key]++;
}
var_dump($result);
/*
Output:
array(2) {
["channel_1"]=>
int(1)
["channel_0"]=>
int(2)
}
*/
You can easily do this without a loop using array_column() and array_count_values().
$reports = array_column($array, 'Report');
$channels = array_column($reports, 'channel');
$counts = array_count_values($channels);
$counts will now equal an array where the key is the channel, and the value is the count.
Array
(
[1] => 1
[0] => 2
)
I need to take an array like this:
Array
(
[0] => Array
(
[county_code] => 54045
[count] => 218
)
[1] => Array
(
[county_code] => 54045
[count] => 115
)
[2] => Array
(
[county_code] => 54051
[count] => 79
)
)
And merge all arrays with the same county_code adding the count, like this:
Array
(
[0] => Array
(
[county_code] => 54045
[count] => 333
)
[1] => Array
(
[county_code] => 54051
[count] => 79
)
)
There will be multiple instances of multiple county codes.
Can anyone point me in the right direction?
Try this out:
// your example array
$array = [
[
"county_code" => 54045,
"count" => 218
],
[
"county_code" => 54045,
"count" => 115
],
[
"county_code" => 54051,
"count" => 79
]
];
// intrim step to collect the count.
$intrimArray = [];
foreach( $array as $data ){
$countyCode = $data["county_code"];
if (!$intrimArray[$countyCode]) {
$intrimArray[$countyCode] = $data["count"];
} else {
$intrimArray[$countyCode] = $intrimArray[$countyCode] + $data["count"];
}
}
// build the final desired array using interim array.
$finalArray = [];
foreach($intrimArray as $countyCode => $totalCount) {
array_push($finalArray, [
"county_code" => $countyCode,
"count" => $totalCount
]);
}
var_dump($finalArray);
As promised:
<?php
$initial_array = [
['country_code' => 54045, 'count' => 218],
['country_code' => 54045, 'count' => 115],
['country_code' => 54051, 'count' => 79],
];
$synth = [];
foreach ($initial_array as $sa) { # $sa: subarray
if (!isset($synth[$sa['country_code']])) {
$synth[$sa['country_code']] = 0;
}
$synth[$sa['country_code']] += $sa['count'];
}
print_r($synth); # Synthesis array: keys are country codes, values are cumulative counts.
# If you need the same format for both the initial and synthesis arrays, then continue with this:
$synth2 = [];
foreach ($synth as $k => $v) {
$synth2[] = ['country_code' => $k, 'count' => $v];
}
print_r($synth2);
?>
A fiddle for this code: https://3v4l.org/M8tkb
Best regards
I have 2 arrays, I'm trying to find any matches and return 'url from $array_full.
I tried array_intersect($array_full, $array_ids), but it doesn't work.
$array_full = array
(
Array
(
'#attributes' => Array
(
'topicid' => 102000,
'url' => 'Velkommen.htm',
'alias' => 'Velkommen'
)
),
Array
(
'#attributes' => Array
(
'topicid' => 130313,
'url' => 'WStation/WAS_Indstillinger.htm',
'alias' => 'WAS_Indstillinger'
)
),
Array
(
'#attributes' => Array
(
'topicid' => 130315,
'url' => 'SPedestal/Applikationer/LoadSharing/Indstillinger.htm',
'alias' => 'LOS_Indstillinger'
)
),
Array
(
'#attributes' => Array
(
'topicid' => 130312,
'url' => 'WStation/WAS_Indstillinger.htm',
'alias' => 'WAS_Indstillinger'
)
)
);
$array_ids = array('130312', '130315');
I expect to get an array of matched url's, like:
array('WStation/WAS_Indstillinger.htm','SPedestal/Applikationer/LoadSharing/Indstillinger.htm')
A simple couple of foreach loops seems the easiest approach
$results = [];
foreach ( $array_full as $a ) {
foreach ( $a as $item ) {
if ( in_array($item['topicid'], $array_ids) ) {
$results[] = $item['url'];
}
}
}
print_r($results);
RESULT
Array
(
[0] => SPedestal/Applikationer/LoadSharing/Indstillinger.htm
[1] => WStation/WAS_Indstillinger.htm
)
You will have to make foreach inside foreach to find item that is matching to ID.
Something like this (not tested, may contain some typos).
foreach($array_ids as $id) {
foreach($array_full as $key => $fullItem) {
if($fillItem['#attributes']['topicid'] != $id) {
continue;
}
//do what you need with $fullItem array
$key; // this is the key you want
}
}
you can use array_map, in_array to get the URL's
$result = [];
array_map(function($v) use ($array_ids,&$result){
$result[] = in_array($v['#attributes']['topicid'], $array_ids) ? $v['#attributes']['url'] : '';
}, $array_full);
Result:-
echo '<pre>';
print_r(array_filter($result));
Array
(
[2] => SPedestal/Applikationer/LoadSharing/Indstillinger.htm
[3] => WStation/WAS_Indstillinger.htm
)
I am trying to put content of one array into the same array. Here I have an array $mclass with values such as
Array
(
[0] => stdClass Object
(
[room_id] => 1,3,5
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
)
You can see I have room_id index with 1,3,5 value. Now, I want to explode the room_id and get duplicate of same array index data with change of room_id and push into the array. and finally delete the current array index such as [0]. Here I want the final result as.
Array
(
[0] => stdClass Object
(
[room_id] => 1
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
[1] => stdClass Object
(
[room_id] => 3
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
[2] => stdClass Object
(
[room_id] => 5
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
)
Here is my code for the same:
if(count($mclass)>0)
{
foreach($mclass as $mclasskey=>$mclass_row)
{
/* Room ID Calculation */
if(isset($mclass[$mclasskey]))
{
$temp_room_id = explode(',',$mclass_row->room_id);
if(count($temp_room_id)>1)
{
foreach($temp_room_id as $trkey=>$tr)
{
if(!in_array($temp_room_id[$trkey], $morning_class_semester))
{
array_push($morning_class_semester,$temp_room_id[$trkey]);
}
}
if(count($morning_class_semester)>0)
{
foreach($morning_class_semester as $mcskey=>$mcs)
{
$index_count = count($new_test);
$test[$index_count] = $mclass[$mclasskey];
$test[$index_count]->room_id = $morning_class_semester[$mcskey];
array_push($new_test,$test[$index_count]);
}
unset($mclass[$mclasskey]);
}
}
}
}
}
The code below does what you're looking for using only arrays. So you'll have to change the array access operators to -> since you're accessing an object. I'd do so, but it would break the example, so I'll leave that up to you.
Code Explained:
Loop through array selecting each subarray (object in your case), explode on the $item('room_id') ... ($item->room_id in your case) ... and create sub arrays, via loop, from that using the data from the original using each key. Remove the original item (which has the combined room_ids) and combine the placeholder and original array.
<?php
//Establish some data to work with
$array = array(
array(
"room_id" => "1,3,5",
"day" => 1,
"class_teacher" => "TEA-2014-2",
"final_exam_date" => "2015-09-21",
));
foreach ($array as $key => $item) {
$placeholder = array();
$ids = explode(',',$item['room_id']);
if (count($ids) > 1) {
foreach ($ids as $id) {
$push = array(
'room_id' => $id,
'day' => $item['day'],
'class_teacher' => $item['class_teacher'],
'final_exam_date' => $item['final_exam_date']
);
array_push($placeholder, $push);
}
$array = array_merge($array, $placeholder);
unset($array[$key]);
}
}
var_dump($array);
?>