ksort on multidimensional array [duplicate] - php

This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 9 months ago.
I have a multidimensional array, and I need to sort that array by a specific key in that array.
I add to the array like this in a for loop
$myArr[$i][0] = $row[1];
$myArr[$i][1] = $row[2];
$myArr[$i][2] = $row[3];
Now lets say that the value of $row[3] is DATE_ATOM.
How can i arrange the completed array by $myArr[$i][2]?
Thanks!

What you are probably looking for is array_multisort(), specifically this example usage (Sorting database results).
For example (based on your code above):
$i = 0;
$myArr = $col1 = $col2 = $col3 = array();
foreach ($rows as $row) {
$myArr[$i][0] = $col1[$i] = $row[1];
$myArr[$i][1] = $col2[$i] = $row[2];
$myArr[$i][2] = $col3[$i] = $row[3];
$i++;
}
array_multisort($col3, SORT_ASC, $myArr);
var_dump($myArr);

Related

PHP : Implode and get the keys of a multidimensional associative array [duplicate]

This question already has answers here:
PHP - Convert multidimensional array to 2D array with dot notation keys
(5 answers)
Closed 2 years ago.
I have a little problem. I want to transform this:
$array['page']['article']['header'] = "Header";
$array['page']['article']['body'] = "Body";
$array['page']['article']['footer'] = "Footer";
$array['page']['news']['header'] = "Header";
$array['page']['news']['body'] = "Body";
$array['page']['news']['footer'] = "Footer";
Into this:
$array['page.article.header'] = "Header";
$array['page.article.body'] = "Body";
$array['page.article.footer'] = "Footer";
$array['page.news.header'] = "Header";
$array['page.news.body'] = "Body";
$array['page.news.footer'] = "Footer";
The number of dimensions is variable and can be times 0 or 10. I don't know if I used the right search term, but Google could not help me so far.
So if someone has a solution for me.
Thanks
You can loop over the array at hand. Now, if the current value is an array, recursively call that array to the function call. On each function call, return an array with key value pairs. When you get the output from your sub-array, attach current key value to all keys of that sub-array returned output.
Snippet:
<?php
function rearrange($array){
$output = [];
foreach($array as $key => $val){
if(is_array($val)){
$out = rearrange($val);
foreach($out as $sub_key => $sub_val){
$output[$key . "." . $sub_key] = $sub_val;
}
}else{
$output[$key] = $val;
}
}
return $output;
}
print_r(rearrange($array));
Demo: https://3v4l.org/40hjK

Two foreach use with a array [duplicate]

This question already has answers here:
How can I loop through a MySQL result set more than once using the mysql_* functions?
(7 answers)
PDO multiple fetching of same query [duplicate]
(2 answers)
Closed 3 years ago.
I have a array and i use two foreach but I be only able to print the first foreach.
$test = $db->query("SELECT * FROM Test");
foreach ($test as $readTest) {
echo $readTest["col1"];
}
foreach ($test as $readTest) {
echo $readTest["col2"];
}
and I try with this:
$test1 = $test;
$test2 = $test;
I expect the output of $readTest["col1"] and $readTest["col2"], but the actual output is $readTest["col1"]
Use #fetchAll to get all your result in a conventional array. You will then be able to loop on them multiple times.
Why use array, when you can print this way:
$test = $db->query("SELECT * FROM Test");
while($PrintTest = $test->fetch_object())
{
echo $PrintTest->col1;
echo $PrintTest->col2;
}
Even if you want to use Arrays, you can do something like this:
$Array1 = array();
$Array2 = array();
$test = $db->query("SELECT * FROM Test");
while($PrintTest = $test->fetch_object())
{
$Array1[] = $PrintTest->col1;
$Array2[] = $PrintTest->col2;
}
And then, you can run through the array with For or Foreach

PHP explode specific text beetwen different elements [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 5 years ago.
I have result
{"success":true,"data":{"id":6583879,"listingId":"11745/3470/OMS"}}
I need to explode it on two arrays:
$id = 6583879;
and
$listid = 11745/3470/OMS
I'd like to avoid counting characters, this response may be another in future. I was thinking about taking:
everything between "id": and comma
everything between "listingId":" and "
PHP code demo
<?php
$json='{"success":true,"data":{"id":6583879,"listingId":"11745/3470/OMS"}}';
$array= json_decode($json,true);
extract($array["data"]);
$first=array("id"=>$id);
$second=array("listingId"=>$listingId);
print_r($first);
print_r($second);
Output:
Array
(
[id] => 6583879
)
Array
(
[listingId] => 11745/3470/OMS
)
just decode the json data
$data = '{"success":true,"data":[{"id":6583879,"listingId":"11745/3470/OMS"}]}';
$arr = json_decode($data);
$id = array();
$listing = array();
for($i=0; $i < count($arr->data); $i++){
$id[$i] = $arr->data[$i]->id;
$listing[$i] = $arr->data[$i]->listingId;
}
//loop array to view data
foreach($id as $value){
echo $value.'<br>';
}
?>
<?php
$json='{"success":true,"data":{"id":6583879,"listingId":"11745/3470/OMS"}}';
$decoded = json_decode($json);
$id = $decoded['data']['id'];
$listingId = $decoded['data']['listingId'];

How to sorting array value by key? [duplicate]

This question already has answers here:
Custom key-sort a flat associative based on another array
(16 answers)
Closed 7 years ago.
I have array like this
<?php
$sliders=array(
1=>array('url'=>"url1.com",'image'=>"img1.jpg"),
2=>array('url'=>"url2.com",'image'=>"img2.jpg"),
3=>array('url'=>"url3.com",'image'=>"img3.jpg"),
4=>array('url'=>"url4.com",'image'=>"img4.jpg"),
5=>array('url'=>"url5.com",'image'=>"img5.jpg")
);
foreach($sliders as $sKey=>$sVal)
{
echo $sKey.'=>'.$sVal['url'].' image=>'.$sVal['image'].'<br>';
}
?>
And my sorting key is
$sort[]='2,4,5,3,1';
And I want result like this.
array(
1=>array('url'=>"url2.com",'image'=>"img2.jpg"),
2=>array('url'=>"url4.com",'image'=>"img4.jpg"),
3=>array('url'=>"url5.com",'image'=>"img5.jpg"),
4=>array('url'=>"url3.com",'image'=>"img3.jpg"),
5=>array('url'=>"url1.com",'image'=>"img1.jpg"));
How can I sorting Array like this?
Thanks.
I cannot believe that you did not find this yourself...
<?php
$newArray = array();
$sortArray = explode(',', $sort[0]);
$i = 1;
foreach ($sortArray as $s) {
if (isset($sliders[$s])) {
$newArray[$i] = $sliders[$s];
$i++;
}
}

Randomizing My Array elements [duplicate]

This question already has answers here:
Displaying and Randomising php Arrays
(4 answers)
Closed 9 years ago.
How do i randomize my array elements and limit number of items to be displayed to 5
My code is:
while($row = mysql_fetch_assoc($result))
{
$new_array[] = $row;
}
echo '<pre>'; print_r(($new_array));
Easiest solution...
array_rand($array, 5);
PHP array_rand()
shuffle($array);
$pointer = 0;
foreach($array as $value) {
if($pointer > 4) break;
echo $value;
$pointer++
}
shuffle will randomize your array, then you start a pointer at 0 and increment it in your foreach loop, if you the pointer is more than 4 you break the foreach loop
as another solution, you could use a for loop
shuffle($array);
for($i = 0; $i < 5; $i++) {
echo $array[$i];
}
and one more solution for limiting, since you're pulling the array for your database by a query, you can limit the number of rows returned by a number you choose by adding LIMIT 5 at the end of your query.

Categories