array manipulation and rearranging - php

Here's my deal.
I have this array:
Array // called $data in my code
(
[0] => Array
(
[name] => quantity
[value] => 0
)
[1] => Array
(
[name] => var_id
[value] => 4
)
[2] => Array
(
[name] => quantity
[value] => 0
)
[3] => Array
(
[name] => var_id
[value] => 5
)
)
which I need it to be like:
Array // called $temp in my code
(
[0] => Array
(
[0] => Array
(
[name] => quantity
[value] => 0
)
[1] => Array
(
[name] => var_id
[value] => 4
)
)
[2] => Array
(
[0] => Array
(
[name] => quantity
[value] => 0
)
[1] => Array
(
[name] => var_id
[value] => 5
)
)
)
and I did it using this code I made:
$data = $_POST['data'];
$temp = array();
foreach($data as $key => $datum)
{
if($key%2 == 0)
{
$temp[$key] = array();
array_push($temp[$key], $datum, $data[$key+1]);
}
}
But I think that my code is some kinda stupid, specially if I have a huge data.
eventually what I want to do is just have each two indexes combined in one array, and I know that there should be something better than my code to do it, any suggestions?

Discover array_chunk()
$temp = array_chunk($data, 2);

$cnt = count($data);
$temp = array();
for ($i = 0; $i < $cnt; $i = $i + 2)
{
$temp[] = array($data[$i], $data[$i+1]);
}

Take a look at array_chunk.
<?php
$array = array(
array(1),
array(2),
array(3),
array(4),
);
print_r(
array_chunk($array, 2, false)
);
/*
Array
(
[0] => Array
(
[0] => Array
(
[0] => 1
)
[1] => Array
(
[0] => 2
)
)
[1] => Array
(
[0] => Array
(
[0] => 3
)
[1] => Array
(
[0] => 4
)
)
)
*/

Related

How to merge two associative arrays

I have two associative arrays like
Array
(
[0] => Array
(
[0] => 2022-01-19
[1] => 6
)
[1] => Array
(
[0] => 2022-01-20
[1] => 1
)
[2] => Array
(
[0] => 2022-01-21
[1] => 1
)
[3] => Array
(
[0] => 2022-01-22
[1] => 2
)
)
and
Array
(
[0] => Array
(
[0] => 2022-01-17
[1] => 6
)
[1] => Array
(
[0] => 2022-01-18
[1] => 1
)
[2] => Array
(
[0] => 2022-01-21
[1] => 1
)
[3] => Array
(
[0] => 2022-01-23
[1] => 2
)
)
I need to merge them with the date and want a result array-like below
Array
(
[0] => Array
(
[0] => 2022-01-17
[1] => 0
[2] => 6
)
[1] => Array
(
[0] => 2022-01-18
[1] => 0
[2] => 1
)
[2] => Array
(
[0] => 2022-01-19
[1] => 6
[2] => 0
)
[3] => Array
(
[0] => 2022-01-20
[1] => 1
[2] => 0
)
[4] => Array
(
[0] => 2022-01-21
[1] => 1
[2] => 1
)
[5] => Array
(
[0] => 2022-01-22
[1] => 2
[2] => 0
)
[6] => Array
(
[0] => 2022-01-23
[1] => 0
[2] => 2
)
)
I tried with the below code but not any success.
$final_array = [];
foreach($openTicket as $val){
$closeTicketNo = 0;
foreach($closeTicket as $value){
if($val[0] == $value[0]){
$closeTicketNo = $value[1];
}
}
$final_array[] = [$val[0],$val[1],$closeTicketNo];
}
I get all the elements from the $openTicket but not get all the elements from a $closeTicket to my result array $final_array
This code first finds all of the unique dates (using array_unique) from the first values in each array (array_column fetches the values and array_merge puts them into 1 array).
Then it indexes each array by the dates (using array_column again).
Finally looping through the unique dates and adding a new element to the output with the values (using ?? 0 so that if no value is present the array is still filled properly)...
$dates = array_unique(array_merge(array_column($openTicket, 0), array_column($closedTicket, 0)));
$open = array_column($openTicket, 1, 0);
$closed = array_column($closedTicket, 1, 0);
$finalArray = [];
foreach ($dates as $date) {
$finalArray[] = [$date, $open[$date] ?? 0, $closed[$date] ?? 0];
}
You can try like this
$array1 = [
['2022-01-19',6],
['2022-01-20',1],
['2022-01-21',0]
];
$array2 = [
['2022-01-17',6],
['2022-01-20',2],
['2022-01-21',1]
];
function mergeMultiple($array1,$array2){
foreach($array1 as $item1){
$mergedArray[$item1[0]] = $item1;
}
foreach($array2 as $item2){
if(isset($mergedArray[$item2[0]])){
array_push($mergedArray[$item2[0]],$item2[1]);
$mergedArray[$item2[0]] = $mergedArray[$item2[0]];
}else{
$mergedArray[$item2[0]] = $item2;
}
}
return array_values($mergedArray);
}
$mergedArray = mergeMultiple($array1,$array2);
ksort($mergedArray);
print_r($mergedArray);

foreach loop to extract and group sub-arrays

Array:
Array
(
[0] => Array
(
[date] => 2018-05-23
[content] => Array
(
[0] => Array
(
[0] => AAAAAA
[1] => BBBBBB
[2] => CCCCCC
[3] => DDDDDD
[4] => EEEEEE
[5] => FFFFFF
[6] => GGGGGG
[7] => HHHHHH
[8] => IIIIII
[9] => JJJJJJ
)
)
)
[1] => Array
(
[date] => 2018-05-22
[content] => Array
(
[0] => Array
(
[0] => KKKKKK
[1] => LLLLLL
[2] => MMMMMM
[3] => NNNNNN
...
I need to be able to create a foreach loop that will create a database record from 3 variables.
foreach #1:
$date = $array['content']['date']; //2018-05-23
$headline = $array['content'][0][$key]; // AAAAAA
$content = $array['content'][0][$key]; // BBBBBB
foreach #2:
$date = $array['content']['date']; //2018-05-23
$headline = $array['content'][0][$key]; // CCCCCC
$content = $array['content'][0][$key]; // DDDDDD
Until it finishes with the first sub-array and then goes to the second array:
foreach #6:
$date = $array['content']['date']; //2018-05-22
$headline = $array['content'][0][$key]; // KKKKKK
$content = $array['content'][0][$key]; // LLLLLL
I've been trying to group the arrays with array_chunk with no success and then I tried to write a small fix to order the array properly with this:
if ($x <= 10) {
if ( $a < 2 ) {
$a++;
} else {
$x++;
$a = 1;
}
$res[$i]['content'][$x][] = ltrim($text);
} else {
$res[$i]['content'][$x][] = ltrim($text);
$x = 0;
}
Result:
[date] => 2018-05-23
[content] => Array
(
[0] => Array
(
[0] => AAAAAA
[1] => BBBBBB
)
[1] => Array
(
[0] => CCCCCC
[1] => DDDDDD
)
[2] => Array
(
[0] => EEEEEE
[1] => FFFFFF
)
[3] => Array
(
[0] => GGGGGG
[1] => HHHHHH
)
Which worked for the first array but all the other arrays lost order and were not categorized properly.
Any ideas how this can be created?
EDIT: content will always have 24 records (0-23), so if divided into chunks we should get 12 array chunks for every content sub-array.
I'm not sure how your DB structure looks like because you didn't mention, but you can do something like that:
<?php
$array = [
[
"date" => "date",
"content" => [["A", "B", "C"]]
],
[
"date" => "date",
"content" => [["E", "F", "G", "H"]]
],
];
$sql = "INSERT INTO table (content, date) VALUES ";
foreach ($array as $key => $item) {
$content = $item["content"][0];
for ($i = 0; $i < count($content); $i += 2) {
$letters = $content[$i];
if (isset($content[$i + 1])) {
$letters .= $content[$i + 1];
}
$sql .= "('$letters', '$item[date]'),";
}
}
$sql = rtrim($sql, ",") . ";";
echo $sql;
Will output:
INSERT INTO table (content, date) VALUES ('AB', 'date'),('C', 'date'),('EF', 'date'),('GH', 'date');
<?php
$collection =
array
(
array
(
'date' => '2018-05-23',
'content' => array
(
array
(
'AAAAAA',
'BBBBBB',
'CCCCCC',
'DDDDDD',
'EEEEEE',
'FFFFFF',
'GGGGGG',
'HHHHHH',
'IIIIII',
'JJJJJJ'
)
)
),
array
(
'date' => '2018-05-22',
'content' => array
(
array
(
'KKKKKK',
'LLLLLL',
'MMMMMM',
'NNNNNN'
)
)
)
);
function getChunks($data){
$result = array();
$length = count($data);
for($i=0;$i<$length;$i += 2){
$result[] = array($data[$i],$data[$i+1]);
}
return $result;
}
function groupContentByDate($collection){
$result = array();
foreach($collection as $each_data){
$result[$each_data['date']] = array('content' => array());
foreach($each_data['content'] as $each_content){
$result[$each_data['date']]['content'] = array_merge($result[$each_data['date']]['content'],getChunks($each_content));
}
}
return $result;
}
echo "<pre>";
print_r(groupContentByDate($collection));
OUTPUT
Array
(
[2018-05-23] => Array
(
[content] => Array
(
[0] => Array
(
[0] => AAAAAA
[1] => BBBBBB
)
[1] => Array
(
[0] => CCCCCC
[1] => DDDDDD
)
[2] => Array
(
[0] => EEEEEE
[1] => FFFFFF
)
[3] => Array
(
[0] => GGGGGG
[1] => HHHHHH
)
[4] => Array
(
[0] => IIIIII
[1] => JJJJJJ
)
)
)
[2018-05-22] => Array
(
[content] => Array
(
[0] => Array
(
[0] => KKKKKK
[1] => LLLLLL
)
[1] => Array
(
[0] => MMMMMM
[1] => NNNNNN
)
)
)
)

count same categories from array and Store in new array with its count and category name

I have one array which I am getting from database query response.
Now I want to count same categories and print in option_name array.
I have tried it with different array functions but want get desire output.
I have one idea to take new array and push it with foreach loop but not much idea of how can i achieve using code. Please help me to solve it.
Array
(
[0] => Array
(
[CNC] => Array
(
[id] => 5
[category_id] => 68
)
[GVO] => Array
(
[option_name] => Actors
)
)
[1] => Array
(
[CNC] => Array
(
[id] => 11
[category_id] => 72
)
[GVO] => Array
(
[option_name] => Cricketers
)
)
[2] => Array
(
[CNC] => Array
(
[id] => 3
[category_id] => 72
)
[GVO] => Array
(
[option_name] => Cricketers
)
)
[3] => Array
(
[CNC] => Array
(
[id] => 4
[category_id] => 74
)
[GVO] => Array
(
[option_name] => Musician
)
)
[4] => Array
(
[CNC] => Array
(
[id] => 7
[category_id] => 76
)
[GVO] => Array
(
[option_name] => Directors
)
)
[5] => Array
(
[CNC] => Array
(
[id] => 6
[category_id] => 76
)
[GVO] => Array
(
[option_name] => Directors
)
)
)
Desire Output:
Array
(
[Actors] => 1
[Cricketers] => 2
[Musician] => 1
[Directors] => 2
)
Thanks in advance!
You simply need to loop through the array using foreach like as
$result = [];
foreach($arr as $k => $v){
if(isset($result[$v['GVO']['option_name']])){
$result[$v['GVO']['option_name']] += 1;
}else{
$result[$v['GVO']['option_name']] = 1;
}
}
print_R($result);
You can count the option_name values by incrementing a counter in an associative array where the key is the option_name:
$counts = [];
foreach($array as $v) {
if(!isset($counts[$v['GVO']['option_name']])) {
$counts[$v['GVO']['option_name']] = 0;
}
$counts[$v['GVO']['option_name']]++;
}
print_r($counts);
Try this:
$new_arr = array();
foreach(array_column($your_arr, 'option_name') as $value){
if(in_array($value, $new_array)){
$new_array[$value] = $new_array[$value]+1;
}else{
$new_array[$value] = 1;
}
}
Output
Array
(
[Actors] => 1
[Cricketers] => 2
[Musician] => 1
[Directors] => 2
)

Ranking array base on key php

I have an array of object "$arr" like this:
Array
(
[0] => stdClass Object
(
[1] => 1
)
[1] => stdClass Object
(
[0] => 1
)
[2] => stdClass Object
(
[4] => 2
)
[3] => stdClass Object
(
[3] => 2
)
[4] => stdClass Object
(
[2] => 3
)
)
What I want to do is rank the value based on the key. If key($arr[$idx+1]) < key($arr[$idx]) then increase value of $arr[idx] by 1. So the results would look like:
Array
(
[0] => stdClass Object
(
[1] => 2
)
[1] => stdClass Object
(
[0] => 1
)
[2] => stdClass Object
(
[4] => 5
)
[3] => stdClass Object
(
[3] => 4
)
[4] => stdClass Object
(
[2] => 3
)
)
this is what I have done so far:
$arrIdx2=[];
foreach($arrIdx as $key=>$value){
$newVal = new stdClass();
$newVal->$key = $value;
$arrIdx2[] = $newVal;
}
foreach($arrIdx2 as $key=>$value){
$i= key((array)$value);
$m = $value->$i; //get the first value
for($j = $key+1; $j< $len; $j++){
$i2 = key((array)$arrIdx2[$j]); //get the key of second value
$n = $arrIdx2[$j]->$i2;
if($n == $m){
if($i2 < $i){
$arrIdx2[$key]->$i += 1;
}
}
}
}
and this is the result I got:
Array
(
[0] => stdClass Object
(
[1] => 2
)
[1] => stdClass Object
(
[0] => 1
)
[2] => stdClass Object
(
[4] => 3
)
[3] => stdClass Object
(
[3] => 2
)
[4] => stdClass Object
(
[2] => 3
)
)
What's the best way to do this? Can anyone guide me? Thanks
Do this with associative array. I can't make an object array
right now. If you provide me the object array then i will update my answer.
Try this:
$arr = array(
array("1" => 1),
array("0" => 1),
array("4" => 2),
array("3" => 2),
array("2" => 3)
);
$out = array();
$first = key(current($arr));
$end = key(end($arr));
foreach($arr as $key => $val){
$comp = (key($val) == $end) ? $end : key($arr[$key+1]);
if($comp <= key($val))
$out[$key][key($val)] = key($val) + 1;
else
$out[$key][key($val)] = $val[key($val)];
}
echo '<pre>';
print_r($out);
Result
Array
(
[0] => Array
(
[1] => 2
)
[1] => Array
(
[0] => 1
)
[2] => Array
(
[4] => 5
)
[3] => Array
(
[3] => 4
)
[4] => Array
(
[2] => 3
)
)
I think you want this, let me know.

Values from multidimensional to array

array fetched somewhere else:
Array
(
[0] => Array
(
[id] => 600000
[name] => test1
)
[1] => Array
(
[id] => 600300
[name] => test2
)
[2] => Array
(
[id] => 600600
[name] => test3
)
)
php:
$leftnav = array("root_id" => 0, "sub_id" => 0, "subsub_id" => 0, "subsubsub_id" => 0);
if (isset($category_data[0]['id']))
$leftnav['root_id'] = $category_data[0]['id'];
if (isset($category_data[1]['id']))
$leftnav['sub_id'] = $category_data[1]['id'];
if (isset($category_data[2]['id']))
$leftnav['subsub_id'] = $category_data[2]['id'];
if (isset($category_data[3]['id']))
$leftnav['subsubsub_id'] = $category_data[3]['id'];
Can the php code be done in a more pretty way? I have tried with array_map but all required keys in $leftnav will not be set.
$i = 0;
foreach( $leftnav as $k => $v ) {
if ( isset($category_data[$i]['id']) ) {
$leftnav[$k] = $category_data[$i]['id'];
}
$i++;
}

Categories