Sorting php array by column in ascending order - php

Array
(
[content_type] => Array
(
[0] => story
[1] => delhi
[2] => tez
)
[type] => Array
(
[0] => video_id
[1] => subcategory
[2] => story_id
)
[fetch_id] => Array
(
[0] => 32
[1] => 32
[2] => 2
)
[order] => Array
(
[0] => 6
[1] => 4
[2] => 5
)
[label] => Array
(
[0] => dsfs fdsf dsf sdf
[1] => dfsdfs
[2] => sdfsdfsd
)
[link] => Array
(
[0] => fsd fsdf sdf
[1] => fsdfsdfdsf
[2] => fsdfdsfds
)
[record] => Array
(
[0] => 10
[1] => 8
[2] => 12
)
)
Above is the array I have to sort this array in the basis of order field and it should shorted all the fields accordingly like below example.
$arr['order'][0] = 4;
$arr['order'][1] = 5;
$arr['order'][2] = 6;
$arr['type'][0] = 'subcategory';
$arr['type'][1] = 'story_id';
$arr['type'][2] = 'video_id';
and so on.....

You can try this -
$new = array();
// Extract and get the keys as values
$order = array_flip($array['order']);
// sort them according to keys
ksort($order);
// loop through main array
foreach($array as $key => $sub_array) {
// loop through order
foreach ($order as $o) {
// store the new value according to order
$new[$key][] = $sub_array[$o];
}
}
Demo

Some lesser solution:
asort($array['order']);
foreach ($array as $key => $subArray) {
$array[$key] = array_replace($array['order'], $subArray);
}
For reset a key sequence you may just to use array_values().

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

Filter multi array

i want to filter this array and get all arrays where [1] => 1. So the php code must return Array [1], [2] and [4]. I have no idea how to do it, so I will be grateful for any help.
Array
(
[0] => Array
(
[0] => 1
[1] => 1
[2] => data1
)
[1] => Array
(
[0] => 2
[1] => 1
[2] => data2
)
[2] => Array
(
[0] => 3
[1] => 2
[2] => data3
)
[3] => Array
(
[0] => 4
[1] => 2
[2] => data4
)
[4] => Array
(
[0] => 5
[1] => 1
[2] => data5
)
[5] => Array
(
[0] => 6
[1] => 3
[2] => data6
)
)
Using a simple foreach loop and appending to a new array when the item matches as required will work:
$in = [
[1,1,'data1'],
[2,1,'data2'],
[3,2,'data3'],
[4,2,'data4'],
[5,1,'data5'],
[6,3,'data6'],
];
$out = [];
foreach ($in as $arr) {
if ($arr[1] == 1) {
$out[] = $arr;
}
}
var_dump($out);
Assuming your parent array was called $master:
foreach ($master as $m)
{
if ($m[1] != 1)
{
unset($m);
}
}
return $master;

[php]How to convert array values to one array value with comma?

Is it possible to connect the key genres, country, in one value
eg [genres] => value1, value2, value3
because there is a problem such that the Values from previous loop are added to the next loop
Here is printscreen http://s12.postimg.org/sv53nakej/Bez_tytu_u.png
1./////////////////////////////////////////////////////////////////////
stdClass Object
(
[title] => Marsjanin
[origTitle] => The Martian
[genres] => Array
(
[0] => Array
(
[key] => 28
[value] => akcja
)
[1] => Array
(
[key] => 33
[value] => sci-fi
)
)
[country] => Array
(
[0] => Array
(
[key] => 53
[value] => USA
)
[1] => Array
(
[key] => 53
[value] => Australia
)
)
)
2./////////////////////////////////////////////////////////////////////
stdClass Object
(
[title] => Pięćdziesiąt twarzy Greya
[origTitle] => Fifty Shades of Grey
[genres] => Array
(
[0] => Array
(
[key] => 16
[value] => melodramat
)
[1] => Array
(
[key] => 33
[value] => sci-fi
)
)
[country] => Array
(
[0] => Array
(
[key] => 53
[value] => USA
)
)
)
This is my code:
foreach( $urll as $urle){
$results = My_Parser::getMovie($urle);
foreach($results as $itemz => $valuez) {
if($itemz=='genres'){
foreach($valuez as $val) {
$genr[] = $val['value'];
}}
}
$genre = implode(', ', $genr);
echo '<tr><th>'.$genre.'</th><th>Importuj</th></tr>';
}
Values from previous loop are added to the next
ex.
A
B
C
D
Result:
A = A
A+B = B
A+B+C = C
A+B+C+D = D
Output [genres]
Array
(
[0] => akcja
[1] => sci-fi
)
Array
(
[0] => akcja / Incorect value added from first array
[1] => sci-fi / Incorect value added from first array
[2] => melodramat
[3] => sci-fi
)
Your $genr is being appended to constantly. Reset it before entering the nested loop:
foreach( $urll as $urle){
...
$genr = array(); // Add this!
foreach($results as $itemz => $valuez) {
...
}
...
$genre = implode(', ', $genr); // Now you're good.
...
}
You need to initialize the array before the foreach of foreach($valuez as $val)
foreach( $urll as $urle){
$results = My_Parser::getMovie($urle);
foreach($results as $itemz => $valuez) {
if($itemz=='genres'){
$genr=array(); //initialization
foreach($valuez as $val) {
$genr[] = $val['value'];
}
$genre = implode(', ', $genr); // use the variable -- As per as your requirement.
echo '<tr><th>'.$genre.'</th><th>Importuj</th></tr>';
}
}
}

Transforming multidimensional arrays

As a stepping stone towards building a bit of json from which to build dependent dropdown, I'd like to transform this array...
Array
(
[0] => Array
(
[id] => 4
[project_id] => 2289
[task] => Drawing
)
[1] => Array
(
[id] => 5
[project_id] => 2289
[task] => Surveying
)
[2] => Array
(
[id] => 6
[project_id] => 2289
[task] => Meeting
)
[3] => Array
(
[id] => 1
[project_id] => 2282
[task] => Folding
)
[4] => Array
(
[id] => 2
[project_id] => 2282
[task] => Printing
)
[5] => Array
(
[id] => 3
[project_id] => 2282
[task] => Cutting
)
)
..to something like this...
Array
(
[0] = Array
(
[project_id] => 2289
[task] => Array
(
[0] => Drawing
[1] => Surveying
[2] => Meeting
)
)
[1] = Array
(
[project_id] => 2282
[task] => Array
(
[0] => Folding
[1] => Printing
[2] => Cutting
)
)
)
Using...
$newArray = array();
foreach ($array as $row)
{
$newArray[$row['project_id']][] = $row['task'];
}
...I'm able to get this...
Array
(
[2289] => Array
(
[0] => Drawing
[1] => Surveying
[2] => Meeting
)
[2282] => Array
(
[0] => Folding
[1] => Printing
[2] => Cutting
)
)
... but I've forgotten how to include the associative keys in the result
You can modify your foreach simply using a index:
$newArray = array();
$index = array();
foreach ($array as $row)
{
$found = array_search( $row['project_id'], $index );
if( $found === False )
{
$found = array_push( $newArray, array( 'project_id' => $row['project_id'] ) )-1;
$index[$found] = $row['project_id'];
}
$newArray[ $found ]['task'][] = $row['task'];
}
eval.in demo
When a new project_id key is found, it is added to $index array, so — searching for it at next loop — I can retrieve the index of corresponding multi-dimensional array.
Just assign them as you would like, the project id in an index, and task continually pushing it there:
$newArray = array();
foreach ($array as $row) {
$newArray[$row['project_id']]['project_id'] = $row['project_id'];
$newArray[$row['project_id']]['task'][] = $row['task'];
}
$newArray = array_values($newArray); // reindex
// removes `$row['project_id']` on each group
Note: Just use array_values to reset the grouping key that you used in the project id grouping.

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

Categories