This question already has answers here:
PHP unique array by value?
(6 answers)
Closed 6 years ago.
I have a PHP array that looks like this,
[["a","b"],["e","j"],["a","s"]]
I need it to look like this,
[["a","b"],["e","j"]]
or this,
[["e","j"],["a","s"]]
I cannot have two inner arrays that contain the same "0" index. It does not matter which inner array is deleted as long as only one remains. How can I go through this array and remove inner arrays that contain the same "0" index?
Thanks!
You could simply loop through the array with two loops. Let's say this is your data:
$data = array(
array('a', 'b'),
array('e', 'j'),
array('a', 's'),
array('a', 't'),
array('c', 't'),
array('a', 'h'),
array('c', 'e'),
array('f', 'g')
);
Then you go ahead and loop through everything, and unset it if it's the same value.
$count = count($data);
foreach($data as $index => $array){
for($i=$index + 1; $i<$count; $i++)
if(isset($array[0]) && isset($data[$i][0]) && $array[0] == $data[$i][0])
unset($data[$i]);
}
The var_dump of $data after the loops would be:
array(4) {
[0]=>
array(2) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
}
[1]=>
array(2) {
[0]=>
string(1) "e"
[1]=>
string(1) "j"
}
[4]=>
array(2) {
[0]=>
string(1) "c"
[1]=>
string(1) "t"
}
[7]=>
array(2) {
[0]=>
string(1) "f"
[1]=>
string(1) "g"
}
}
<?php
$array = [["a","b"],["e","j"],["a","s"]];
$values = array();
foreach ($array as $key => $arrayChild) {
foreach ($arrayChild as $val) {
if (in_array($val, $values)) {
unset($array[$key]);
}
$values[] = $val;
}
}
print_r($array);
?>
Result:
Array (
[0] => Array ( [0] => a [1] => b )
[1] => Array ( [0] => e [1] => j )
)
Related
I am trying to explode the JSON file below with the 2 arrays but keep getting an output of..
Array
(
[0] =>
)
Array
(
[0] =>
)
What am I doing wrong?
[0]=>
array(2) {
["question_id"]=>
string(2) "88"
["weight"]=>
string(1) "5"
}
[1]=>
array(2) {
["question_id"]=>
string(2) "89"
["weight"]=>
string(1) "5"
$quest_id = $data["question_id"];
$quest_points = $data["weight"];
$quest_id_array = explode(" ,", $quest_id);
$quest_points_array = explode(" ,", $quest_points);
print_r($quest_id_array);
print_r($quest_points_array);
Assuming $data is the array you show at the top, it's not an array containing comma-separated strings. It's a 2-dimensional array, so you need to loop over it and push the values onto the new arrays.
$quest_id_array = [];
$quest_points_array = [];
foreach ($data as $val) {
$quest_id_array[] = $val['question_id'];
$quest_points_array[] = $val['weight'];
}
This question already has answers here:
Transpose 2d array, join second level with commas, and join first level with pipes
(5 answers)
Closed 7 months ago.
I have the following array.
$a = array("Algebra", "Arithmetic");
$b = array("08/01/2020", "08/02/2019");
$c = array("08/01/2020", "08/02/2019");
print_r($a);
print_r($b);
print_r($b);
and the output is
Array(
[0] => Algebra
[1] => Arithmetic
)
Array(
[0] => 08/01/2020
[1] => 08/01/2019
)
Array(
[0] => 08/02/2020
[1] => 08/02/2019
)
And I want Array in the following structure.
Array(
[0] => Algebra,08/01/2020,08/02/2020
[1] => Arithmetic,08/01/2019,08/02/2019
)
I have tried $results = array_merge_recursive($a, $b, $c); but its not giving desire output.
Thanks for help in advance.
A simple foreach loop will suffice
$a = array("Algebra", "Arithmetic");
$b = array("08/01/2020", "08/02/2019");
$c = array("08/01/2020", "08/02/2019");
foreach( $a as $i=>$v ) {
$new[] = sprintf( '%s,%s,%s', $v, $b[$i], $c[$i] );
}
Firstly, when you find yourself using sequentially-named variables it almost always means that they should actually be an array:
$a = array("Algebra", "Arithmetic");
$b = array("08/01/2020", "08/02/2019");
$c = array("08/01/2020", "08/02/2019");
$better_array = [$a, $b, $c];
var_dump($better_array);
Output:
array(3) {
[0]=>
array(2) {
[0]=>
string(7) "Algebra"
[1]=>
string(10) "Arithmetic"
}
[1]=>
array(2) {
[0]=>
string(10) "08/01/2020"
[1]=>
string(10) "08/02/2019"
}
[2]=>
array(2) {
[0]=>
string(10) "08/01/2020"
[1]=>
string(10) "08/02/2019"
}
}
Once they're in an proper array you can use array_column()
$out = [];
for($i=0, $c=count($better_array[0]); $i < $c; ++$i) {
$out[] = array_column($better_array, $i);
}
var_dump($out);
Output:
array(2) {
[0]=>
array(3) {
[0]=>
string(7) "Algebra"
[1]=>
string(10) "08/01/2020"
[2]=>
string(10) "08/01/2020"
}
[1]=>
array(3) {
[0]=>
string(10) "Arithmetic"
[1]=>
string(10) "08/02/2019"
[2]=>
string(10) "08/02/2019"
}
}
And if that comma-delimited string is what you actually want, then use implode():
$out = [];
for($i=0, $c=count($better_array[0]); $i < $c; ++$i) {
$out[] = implode(',', array_column($better_array, $i));
}
var_dump($out);
Output:
array(2) {
[0]=>
string(29) "Algebra,08/01/2020,08/01/2020"
[1]=>
string(32) "Arithmetic,08/02/2019,08/02/2019"
}
Lastly, you should avoid print_r() as it tends to produce misleading output. Eg: https://3v4l.org/ThSLb
You don't get anything built-in for this purpose. You need to build a custom function for this. You can try this-
<?php
$a = array("Algebra", "Arithmetic");
$b = array("08/01/2020", "08/01/2019");
$c = array("08/02/2020", "08/02/2019");
function mergeAssoc()
{
// You can get variable number of arguments|array by this.
$args = func_get_args();
$master = array();
foreach ($args as $arg)
{
foreach ($arg as $i => $v)
{
$master[$i][] = $v;
}
}
return $master;
}
$res = mergeAssoc($a, $b, $c);
print_r($res);
Note: It will return a multidimensional array. Not an array of comma-separated values.
Output:
Array
(
[0] => Array
(
[0] => Algebra
[1] => 08/01/2020
[2] => 08/02/2020
)
[1] => Array
(
[0] => Arithmetic
[1] => 08/01/2019
[2] => 08/02/2019
)
)
and if we use foreach then our desire output will be there with array separated by comma.
foreach ($res as $key => $value) {
$result[] = implode(',', $value);
}
and output of print_r($result); is
Array
(
[0] => Algebra,08/01/2020,08/02/2020
[1] => Arithmetic,08/01/2019,08/02/2019
)
This question already has answers here:
Combine two arrays
(11 answers)
Closed 5 months ago.
how can we join this two arrays into one array
for this, I had done my code like this and got the output as shown below
$groups_array = array_map('trim',explode(',', $tt));
$tt looks like this string(5) "11:00" string(5) "10:00"
array(1) { [0]=> string(5) "11:00" } array(1) { [0]=> string(5) "10:00" }
need desired output to look like
array(1) { [0]=> string(5) "11:00",[1]=> string(5) "10:00" }
My code is here please have a look
<?php $time_booked=$this->Hospital_model->get_already_booked_time($d,$timeslot->doctor_id);
foreach($time_booked as $index1=> $t) {
$tt=$t->time;
$groups_array = array_merge(array_map('trim',explode(',', $ttt)));
} ?>
my var_dump($time_booked) looks like this
array(2) { [0]=> object(stdClass)#40 (1) { ["time"]=> string(5) "11:00" } [1]=> object(stdClass)#41 (1) { ["time"]=> string(5) "10:00" } }
What about array_merge() with array_map()
$groups_array = array_merge(array_map('trim',explode(',', $tt)));
Output:-https://eval.in/1012484
By looking your edit in your question no need to do any extra stuff, just create an array and add values to it
<?php
$groups_array = []; //create array
$time_booked=$this->Hospital_model->get_already_booked_time($d,$timeslot->doctor_id);
foreach($time_booked as $index1=> $t) {
$groups_array[] =$t->time; //add values to array
}
var_dump($groups_array);
?>
What about array_merge ? That should give you the result.
http://php.net/manual/de/function.array-merge.php
EDIT:
$tt = ['11:00'];
$tt2 = ['10:00'];
$result = array_merge($tt,$tt2);
var_dump($result);
Result is
array(2) {
[0]=>
string(5) "11:00"
[1]=>
string(5) "10:00"
}
Is that not what you meant ?
Suppose you have two array which look like
$array1 = array(0 => "10:00 am");
$array2 = array(0 => "11:00 am");
and you want to join and want output like: Array ( [0] => 10:00 am [1] => 11:00 am )
then you can use array_merge option
$array3 = array_merge($array1, $array2);
If you print print_r($array3);
output will be
Array ( [0] => 10:00 am [1] => 11:00 am )
I have an array stored in a variable $data. The array has names in the first row and a value in the second row. The array is very big so I need a way to take the five highest values from it and the name from those value. For example I have this array:
[0]=>
array(1447) {
[1]=>
array(3) {
[0]=>
string(11) "Cris"
[2]=>
string(1) "11"
}
[2]=>
array(3) {
[0]=>
string(7) "Alan"
[2]=>
string(1) "28"
}
[3]=>
array(3) {
[0]=>
string(6) "Alex"
[2]=>
string(1) "50"
}
[4]=>
array(3) {
[0]=>
string(6) "Zone"
[1]=>
string(1) "22"
}
[5]=>
array(3) {
[0]=>
string(6) "Ana"
[2]=>
string(1) "1"
}
[6]=>
array(3) {
[0]=>
string(6) "Fisca"
[1]=>
string(1) "5"
}
In this case I should display: Alex 50, Alan 28, Zone 22, Cris 11 and Fisca 5. I tried to find a solution but I don't know how should I make a top of array values. Can you help me please? Thank you in advance.
First sort your array and then slice the top 5:
DEMO
usort($data, function ($a, $b) {
return $b[1] - $a[1];
}); //Sort your array
$resultant = array_slice($data,0,5); //Pick top 5
Note: If your index used for comparison differs, then change your return statement to:
return (isset($b[1])?$b[1]:$b[2]) - (isset($a[1])?$a[1]:$a[2]);
Example:
<?php
$data = [
['Cris', 11],
['Alan', 28],
['Alex', 50],
['Zone', 22],
['Ana', 1]
];
usort($data, function ($a, $b) {
return $b[1] - $a[1];
});
print_r(array_slice($data,0,5));
Result:
Array
(
[0] => Array
(
[0] => Alex
[1] => 50
)
[1] => Array
(
[0] => Alan
[1] => 28
)
[2] => Array
(
[0] => Zone
[1] => 22
)
[3] => Array
(
[0] => Cris
[1] => 11
)
[4] => Array
(
[0] => Ana
[1] => 1
)
)
DEMO
You can use this to get the 5 highest values of your array:
<?php
function compare($a, $b) {
if ($a[1] == $b[1]) {
return 0;
}
return ($a[1] > $b[1]) ? -1 : 1;
}
usort($theBigArray, "compare");
$fiveHighestValues = array_slice($theBigArray, 0, 5);
?>
($theBigArray being your array)
And then, you can loop through the $fiveHighestValues var to display the five elements as you want, e.g.:
<?php
foreach($fiveHighestValues as $value) {
echo $value[0] .' has the value '. $value[1];
// output: Alex has the value 50
}
?>
I would first sort the array like this
function mySort($a, $b) {
return $b[1] - $a[1];
}
usort($arr, 'mySort');
Then you can just pop the first 5 values - they are the highest.
You've written that 'The array has names in the first row and a value in the second row.', but I can see that for 'Zone' the index '1' is set not '2', so in your sorting function you might need to add some simple checking, maybe something like this:
function mySortWithCheck($a, $b) {
if (isset($b[1])) {
$valB = $b[1];
} else {
$valB = $b[2];
}
if (isset($a[1])) {
$valA = $a[1];
} else {
$valA = $a[2];
}
return $valB - $valA;
}
<?php
$data = array(
array("Cris", "11"),
array("Alan", "28"),
array("Alex","50"),
array("Zone","22"),
array("Ana","1")
);
var_dump($data);
function custom_array_sort($a, $b) {
return $b[1] - $a[1];
}
usort($data,'custom_array_sort');
$sorted = array_slice($data,0,5);
var_dump($sorted);
?>
i have array an with this result :
Array
(
[A] => Array
(
[0] => A
[1] => B
[2] => C
)
[B] => Array
(
[0] =>AA
[1] =>BB
[2] =>CC
)
[C] => Array
(
[0] =>AAA
[1] =>BBB
[2] =>CCC
)
)
i want to get like rows and print like with this result to each row:
A AA AAA
B BB BBB
C CC CCC
how to use foreach to print that result?
foreach ($result as $kk => $arr)
{
foreach($arr as $k=>$v)
{
if ( $k == 'A')
echo $arr[0];
if ( $k == 'B')
echo $arr[1];
if ( $k == 'B')
echo $arr[2]."<br />";
}
}
Create a new tmp variable for storing our new order.
$tmp = array();
How deep will the array go? In your example we go down 3 levels..
$depth = 3;
The array you want to sort
$result = array(
'a' => array( 'a', 'b', 'c' ),
'b' => array( 'aa', 'bb', 'cc' ),
'c' => array( 'aaa', 'bbb', 'ccc' ),
);
For each level in $result down to $depth.
for ($i=0; $i<$depth; $i++)
{
// Loop true our results and push them in to the right position in our $tmp array.
foreach ($result as $row)
{
$tmp[$i][] = $row[$i];
}
}
Output var_dump($tmp):
array(3) {
[0]=>
array(3) {
[0]=>
string(1) "a"
[1]=>
string(2) "aa"
[2]=>
string(3) "aaa"
}
[1]=>
array(3) {
[0]=>
string(1) "b"
[1]=>
string(2) "bb"
[2]=>
string(3) "bbb"
}
[2]=>
array(3) {
[0]=>
string(1) "c"
[1]=>
string(2) "cc"
[2]=>
string(3) "ccc"
}
}
And of course.. to print out your re-ordered array with foreach:
foreach($tmp as $row) {
echo "{$row[0]} {$row[1]} {$row[2]}";
}
will give you:
a aa aaa
b bb bbb
c cc ccc
If you denote your input as $hash, then $result will have the array in the form that you need:
$arr = array_values($hash);
$result = array();
$len = count($arr);
$lenNested = count($arr[0]);
for($i = 0; $i < $len; $i++){
for($j = 0; $j < $lenNested; $j++){
$result[$j][$i] = $arr[$i][$j];
}
}
This is just transposition of $hash. Now you can print out $result line by line.