foreach loop to extract and group sub-arrays - php

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

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

php array unset not working as expected

I have an array of records I want to create a separate array of skills and want to remove duplicate values, unset not providing desired result somehow, I am not able to find out what's wrong. For example I have record (a) in first skills array at index 0 and I have same record in last skills array at index 1 , I just want to remove any duplicate records but unset removing other records also.
$x = 0;
$y = 0;
$z = 0;
$data = array();
$all_data = array ( 0 => array ( "fname" => "Ann", "skills" => array ( 0 => "a", 1 => "b" )),
1 => array ( "fname" => "Bxx", "skills" => array ( 0 => "c", 1 => "d" )),
2 => array ( "fname" => "Sdd", "skills" => array ( 0 => "e", 1 => "a" ))
);
while( $x < count($all_data)){
while($y < count($all_data[$x]['skills'])){
$data[$x] = $all_data[$x]['skills'];
if (in_array($data[$x][$y], $data[$x])){
unset($data[$x][$y]);
}
$y++;
}
$y = 0;
$x++;
}
The result I am getting is this
Array
(
[0] => Array
(
[0] => a
)
[1] => Array
(
[0] => c
)
[2] => Array
(
[0] => e
[1] => a
)
)
I am expecting
Array
(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[0] => c
[1] => d
)
[2] => Array
(
[0] => e
)
)
You could try something like this :
$keys=[];
foreach ($all_data as $index1 => $item) {
if (!isset($item['skills'])) continue;
foreach ($item['skills'] as $index2 => $value) {
if (!in_array($value, $keys)) {
$data[$index1][] = $value ;
$keys[] = $value ;
}
}
}
unset($keys);
print_r($data);
Outputs :
Array
(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[0] => c
[1] => d
)
[2] => Array
(
[0] => e
)
)

Rearrange multi Arrays in PHP

I have the array about:
Array
(
[id] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[product] => Array
(
[0] => t-shirt
[1] => earing
[2] => clock
)
[price] => Array
(
[0] => 100.00
[1] => 32.00
[2] => 898.00
)
)
I want to do this:
Array
(
[0] => Array
(
[0] => 1
[1] => t-shirt
[2] => 100.00
)
[1] => Array
(
[0] => 2
[1] => earing
[2] => 32.00
)
[2] => Array
(
[0] => 3
[1] => clock
[2] => 898.00
)
)
You can try with:
$input = array( /* your input array */ );
$output = array();
foreach ($input as $data) {
for ($i = 0; $i < count($data); $i++) {
if (!isset($output[$i])) {
$output[$i] = array();
}
$output[$i][] = $data[$i];
}
}
Well or like this.
$test = array(
'id' => array(
1,2,3
),
'product' => array(
'tshirt', 'ewew', 'shorts'
),
'price' => array(
'10.00', '20.00', '30.00'
)
);
$newarray = array();
foreach($test['id'] as $k => $v){
$newarray[$k] = array(
$v, $test['product'][$k], $test['price'][$k]
);
}
echo '<pre>';
print_r($newarray);
Example live

Create a multidimensional array in PHP by separating each line based off a specific value

This is the array I have:
Array
(
[0] => name:string:255
[1] => weight:integer
[2] => description:string:255
[3] => age:integer
)
I want it to look like this
NewArray
(
[0] => Array
(
[0] => name
[1] => string
[2] => 255
[1] => Array
(
[0] => weight
[1] => integer
[2] => Array
(
[0] => description
[1] => string
[2] => 255
[3] => Array
(
[0] => age
[1] => integer
)
Or better yet, I would prefer this result. Making two separate arrays based off the number of groups.
NewArray1
(
[0] => Array
(
[0] => name
[1] => string
[2] => 255
[1] => Array
(
[0] => description
[1] => string
[2] => 255
)
NewArray2
(
[0] => Array
(
[0] => weight
[1] => integer
[1] => Array
(
[0] => age
[1] => integer
)
I have tried exploding and implode and foreaching but I'm not quite getting the result I want.
Use array_reduce() to build a new array while iterating over the old, splitting it up by type:
$array = [
'name:string:255',
'weight:integer',
'description:string:255',
'age:integer',
];
$result = array_reduce($array, function(&$result, $item) {
$parts = explode(':', $item, 3);
$result[$parts[1]][] = $parts;
return $result;
}, []);
Try this:
<?php
$array = array("name:string:255", "weight:integer", "description:string:255", "age:integer");
function map_func($value) {
return explode(':', $value);
}
$newArray = array_map(map_func, $array);
echo "Output 1:\n";
print_r($newArray);
$sorted = array();
foreach($newArray as $el)
$sorted[$el[1]][] = $el;
echo "Output 2:\n";
print_r($sorted);
Output:
Output 1:
Array
(
[0] => Array
(
[0] => name
[1] => string
[2] => 255
)
[1] => Array
(
[0] => weight
[1] => integer
)
[2] => Array
(
[0] => description
[1] => string
[2] => 255
)
[3] => Array
(
[0] => age
[1] => integer
)
)
Output 2:
Array
(
[string] => Array
(
[0] => Array
(
[0] => name
[1] => string
[2] => 255
)
[1] => Array
(
[0] => description
[1] => string
[2] => 255
)
)
[integer] => Array
(
[0] => Array
(
[0] => weight
[1] => integer
)
[1] => Array
(
[0] => age
[1] => integer
)
)
)
I doubt the following is the best solution but it does return what you wanted.
$array = array(
"0" => "name:string:255",
"1" => "weight:integer",
"2" => "description:string:255",
"3" => "age:integer"
);
foreach ($array as $key => $val) {
foreach (explode(':', $val) as $part) {
$new_array[$key][] = $part;
}
}
print_r($new_array);
above returns the following.
Array
(
[0] => Array
(
[0] => name
[1] => string
[2] => 255
)
[1] => Array
(
[0] => weight
[1] => integer
)
[2] => Array
(
[0] => description
[1] => string
[2] => 255
)
[3] => Array
(
[0] => age
[1] => integer
)
)
So you have a 1-dimentional array of strings ($arr01) . strings are separated by :
and you need to have a 2-dimentional array ($arr02) where the second dimension is an array of strings composed by splitting the initial set of strings based on their separator character :
$arr01 = array("name:string:255", "weight:integer", "description:string:255", "age:integer");
$arr02 = array(array());
for($i=0; $i<sizeof($arr01); $i++) {
$arr02[$i] = explode(":",$arr01[$i]);
}
display the two arrays....
echo "array 01: <br>";
for($i=0; $i<sizeof($arr01); $i++) {
echo "[".$i."] ".$arr01[$i]."<br>";
}
echo "<br><br>";
echo "array 02: <br>";
for($i=0; $i<sizeof($arr01); $i++) {
echo "[".$i."] ==> <br>";
for($j=0; $j<sizeof($arr02[$i]); $j++) {
echo " [".$j."] ".$arr02[$i][$j]." <br>";
}
}
echo "<br><br>";

array manipulation and rearranging

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
)
)
)
*/

Categories