php array data sorting - php

Have troubles with sorting data in array, after I loop through a table in my database these are result:
Array
(
[0] => Array
(
[model] => Cars
[number] => 101
)
[1] => Array
(
[model] => Cars
[number] => 113
)
[2] => Array
(
[model] => Train
[number] => 220
)
)
From data above, how do I get them to be like below?
Array
(
[0] => Cars
(
[0] => 101
[1] => 113
)
[2] => Train
(
[0] => 220
)
)
Thank you.

if cars,trains ... are in a column in your table you can use GROUP BY to get data from database and then use it like that array you want.
if not use this loop :
$array; //your array
$new_array=[];
foreach($array as $i => $item){
if(!array_key_exists($item[model],$new_array))
$new_array[$item[model]]=[];
$new_array[$item[model]][]=$item[number];
}

You can use array_reduce to group your array.
Note: I used model as the key of the $result
$arr = //your array
$result = array_reduce($arr, function($c, $o){
$c[$o['model']][] = $o['number'];
return $c;
},array());
echo "<pre>";
print_r( $result );
echo "</pre>";
This will result to:
Array
(
[Cars] => Array
(
[0] => 101
[1] => 113
)
[Train] => Array
(
[0] => 220
)
)
Doc: array_reduce()

Related

How to split string into an associative array which has arrays within arrays

I have the following string: names=bob;mike;sam&age=30;23;22&fav-nums=200;300;400
I was wondering if there is a function which can split this into an associative array which as arrays within it. For example
Array (
["name"] => Array
(
bob,
mike,
sam
)
["age"] => Array
(
30,
23,
22
)
["fav-nums"] => Array
(
200,
300,
400
)
)
You can user parse_str() and explode() functions to achieve this.
Steps:
1) Use parse_str() function, it will split your string into associative array.
2) Now loop over it and go for key values.
3) keys will be the required keys (names, age and fav-nums) and you want values to be array.
4) explode() the values with ; and you will get required values.
Working code:
$str = "names=bob;mike;sam&age=30;23;22&fav-nums=200;300;400";
parse_str($str, $output);
$arr = [];
if (! empty($output)) {
foreach ($output as $key => $value) {
$arr[$key] = explode(';', $value);
}
}
echo '<pre>';print_r($arr);echo '</pre>';
Output:
Array
(
[names] => Array
(
[0] => bob
[1] => mike
[2] => sam
)
[age] => Array
(
[0] => 30
[1] => 23
[2] => 22
)
[fav-nums] => Array
(
[0] => 200
[1] => 300
[2] => 400
)
)
Not sure if there is a direct method of creating the sub-arrays, but parse_str() will split the initial string by & and create the starting point, then process each element with explode() (and array_walk()) to create the sub-arrays.
$start = 'names=bob;mike;sam&age=30;23;22&fav-nums=200;300;400';
parse_str($start, $output);
array_walk($output, function ( &$data ) { $data = explode(";", $data); });
print_r($output);
which gives...
Array
(
[names] => Array
(
[0] => bob
[1] => mike
[2] => sam
)
[age] => Array
(
[0] => 30
[1] => 23
[2] => 22
)
[fav-nums] => Array
(
[0] => 200
[1] => 300
[2] => 400
)
)
You can use array_map function in order to traverse the whole array as it boost up speed of your code. Also parse_str is always use in order to read Query String and convert it in array form.
$text = 'names=bob;mike;sam&age=30;23;22&fav-nums=200;300;400';
parse_str($text, $outputArray);
$array = [];
if(!empty($outputArray)) {
$array = array_map(
function($v) {
return explode(';', $v);
}, $outputArray
);
}
echo"<pre>";
print_r($array);
The result shows
Array
(
[names] => Array
(
[0] => bob
[1] => mike
[2] => sam
)
[age] => Array
(
[0] => 30
[1] => 23
[2] => 22
)
[fav-nums] => Array
(
[0] => 200
[1] => 300
[2] => 400
)
)

manipulating multidimensional array

I have a multi-dimensional array. Since the value of the string "volvo" is present twice, I want to combine those keys. Here's the source array:
Array
(
[0] => Array
(
[0] => Volvo
[1] => 22
)
[1] => Array
(
[0] => BMW
[1] => 15
)
[2] => Array
(
[0] => Saab
[1] => 5
)
[3] => Array
(
[0] => Volvo
[1] => 17
)
)
and I'd like to convert it to this one:
Array
(
[0] => Array
(
[0] => Volvo
[1] => 39
)
[1] => Array
(
[0] => BMW
[1] => 15
)
[2] => Array
(
[0] => Saab
[1] => 5
)
)
I think this would make more sense to return an associated array, that way you can do $arr["volvo"], if you're fine with an associated array, just remove the second foreach loop.
If not, this will get the correct output:
<?php
$arr = Array (
Array (
"Volvo",
22
),
Array (
"BMW",
15
),
Array (
"Saab",
5
),
Array (
"Volvo",
17
)
);
$tmpNewArr = Array();
foreach ($arr as $ele) {
if (!isset($arr[$ele[0]])) {
$tmpNewArr[$ele[0]] = 0;
}
$tmpNewArr[$ele[0]] += $ele[1];
}
$newArr = [];
foreach ($tmpNewArr as $key => $ele) {
array_push($newArr,[$key,$ele]);
}
var_dump($newArr);
?>
Here's an eval.in:
https://eval.in/766340
$keyValueCars = [];
foreach($cars as $car){
$brand = $car[0];
$total = $car[1];
if(!isset($keyValueCars[$brand])){
$keyValueCars[$brand] = total;
}
else{
$keyValueCars[$brand] += total;
}
}
You could use
array_unique(Your_array, SORT_REGULAR);

I want replace index array. example $array[x][y] to $array[y][x]

Example. I have:
Array (
[0] => Array (
[comments_id] => 1
[comments_text] => blabla1
)
[1] => Array (
[comments_id] => 2
[comments_text] => blabla2
)
)
I want have:
Array (
[comments_id] => Array (
[0] => 1
[1] => 2
)
[comments_text] => Array (
[0] => blabla1
[1] => blabla2
)
In simplified wants to replace
$array[x][y] to $array[y][x]
I writing in php.
you can do it like this
// the final array which will hold your result array
// considering $results contains your previous array
$final_array = array();
foreach($results as $result) {
$final_array['comments_id'][] = $result['comments_id'];
$final_array['comments_text'][] = $result['comments_text'];
}

How to explode ans change the array values into key?

I am having an array like this.
Array
(
[0] => Array
(
[0] => a~226
[1] => a~228
)
[1] => Array
(
[0] => b~123
[1] => b~209
)
[2] => Array
(
[0] => c~161
[1] => c~140
)
)
I want to explode this array using ~ symbol and i want value to be a key in php array.i want an array like this.Kindly help me write the code.
Array
(
[0] => Array
(
[a] => 226
[a] => 228
)
[1] => Array
(
[b] => 123
[b] => 209
)
[2] => Array
(
[c] => 161
[c] => 140
)
)
Thanks in advance...
You cannot have such an array.
The keys must be unique (Like Mark Baker say).
You can have something like this:
Array
(
[a] => Array
(
[0] => 226
[1] => 228
)
[b] => Array
(
[0] => 123
[1] => 209
)
[c] => Array
(
[0] => 161
[1] => 140
)
)
The code to do this:
$array = array(
array("a~226", "a~228"),
array("b~123", "b~209"),
array("c~161", "c~140")
);
$result = array();
foreach($array as $inner_array) {
foreach($inner_array as $value) {
$spitted = explode("~", $value);
$result[$spitted[0]][] = end($spitted);
}
}
An working example: http://codepad.viper-7.com/znhhqB
try this
$arr_new = array();
foreach($arr_main as $key=>$arr)
{
foreach($arr as $k=>$val)
{
$str = explode("~",$val);
$arr_new[$key][$str[0].$k]=$str[1];
}
}
will maintain the index as a0, a1

Group values from array

I have this array:
SimpleXMLElement Object
(
[id] => Array
(
[0] => Koala.jpg
[1] => Jellyfish.jpg
)
[desc] => Array
(
[0] => koaladesc
[1] => jelly desc
)
[qtidade] => Array
(
[0] => 1
[1] => 5
)
I need create some php function that help me group the values like this:
[0] => Array
(
[0] => Koala.jpg
[1] => koaladesc
[2] => 1
)
[1] => Array
(
[0] => Jellyfish
[1] => jelly desc
[2] => 5
)
Could anyone help me?
Something like this should do the trick, but it's localized to what you're asking based on the vagueness of your question:
$new_array = array();
foreach($simple_xml_object as $obj) {
if(is_array($obj)) {
for($i = 0; $i < count($obj); $i++) {
$new_array[$i][] = $obj[$i];
}
}
}
I would suggest looking at the documentation on the foreach() construct, as well as looking over the SimpleXML manual.
So, you want to tranpose an array. Here's a magical way of transposing rectangular arrays:
array_unshift($array, null);
$array = call_user_func_array('array_map', $array);
let's suppose your array is saved in variable $arrayValues
$arrayValues = [id] => Array
(
[0] => Koala.jpg
[1] => Jellyfish.jpg
)
[desc] => Array
(
[0] => koaladesc
[1] => jelly desc
)
[qtidade] => Array
(
[0] => 1
[1] => 5
)
now you need to create the following code:
foreach($arrayValues as $array)
{
echo $array->id;
echo $array->desc;
echo $array->qtidade;
}
this may work well for you.

Categories