I have the following array structure:
Array
(
[0] => Array
(
[id] => 83
[parent_id] => 0
[title] => Questionnaire one
)
[1] => Array
(
[id] => 84
[parent_id] => 0
[title] => Questionnaire two
)
[2] => Array
(
[id] => 85
[parent_id] => 83
[title] => Questionnaire three
)
)
I want to re-structure the array so child items are listed under their parents. For example:
Array
(
[0] => Array
(
[id] => 83
[parent_id] => 0
[title] => Questionnaire one
)
[1] => Array
(
[id] => 85
[parent_id] => 83
[title] => Questionnaire three
)
[2] => Array
(
[id] => 84
[parent_id] => 0
[title] => Questionnaire two
)
)
I've searched previous questions but found none of them actually achieve the above.
Can someone please help me with this?
Thanks
You can try
$array = Array(
"0" => Array("id" => 83,"parent_id" => 0,"title" => "Questionnaire one"),
"1" => Array("id" => 84,"parent_id" => 0,"title" => "Questionnaire two"),
"2" => Array("id" => 85,"parent_id" => 83,"title" => "Questionnaire three"));
$id = array_map(function ($item) {return $item["id"];}, $array);
$parent = array_filter($array, function ($item){return $item['parent_id'] == 0;});
$lists = array();
foreach ($parent as $value)
{
$lists[] = $value ;
$children = array_filter($array, function ($item) use($value) {return $item['parent_id'] == $value['id'];});
foreach($children as $kids)
{
$lists[] = $kids ;
}
}
echo "<pre>";
print_r($lists);
Output
Array
(
[0] => Array
(
[id] => 83
[parent_id] => 0
[title] => Questionnaire one
)
[1] => Array
(
[id] => 85
[parent_id] => 83
[title] => Questionnaire three
)
[2] => Array
(
[id] => 84
[parent_id] => 0
[title] => Questionnaire two
)
)
You could use uksort(). Heres a DEMO.
function cmp($a, $b) {
if ($stock[$a] != $stock[$b]) return $stock[$b] - $stock[$a];
return strcmp($a, $b);
}
$a = array(5 => 'apple', 1 => 'banana', 6 => 'orange', 2 => 'kiwi');
uksort($a, "cmp");
foreach ($a as $key => $value) {
echo "$key: $value\n";
}
Related
i have array like this:
(
[0] => Array
(
[id] => 1
[name] => Bazowa
[parent_id] => 0
)
[1] => Array
(
[id] => 2
[name] => Główna
[parent_id] => 1
)
[2] => Array
(
[id] => 12
[name] => PlayStation
[parent_id] => 2
)
[3] => Array
(
[id] => 13
[name] => Xbox
[parent_id] => 2
)
[4] => Array
(
[id] => 14
[name] => Nintendo
[parent_id] => 2
)
[5] => Array
(
[id] => 15
[name] => PC
[parent_id] => 2
)
)
and i want sort this array like tree on screenshot below:
Screen of tree what I want
i trying use this Sort array values based on parent/child relationship
foreach($xml->children()->children() as $value) {
if($value->active == 1) {
$categories[] = [
'id' => (int) $value->id,
'name' => (string) $value->name->language,
'parent_id' => (int) $value->id_parent
];
}
}
$parent_ids = [];
$parents = ['' => []];
foreach($categories as $val) {
$parents[$val['parent_id']][] = $val;
}
$sorted = $parents[''];
dump($parents); exit;
for($val = reset($sorted); $val; $val = next($sorted)) {
if(isset($parents[$val[0]])) {
foreach($parents[$val[0]] as $next) {
$sorted[] = $next;
}
}
}
The most important thing for me is that everything displays well in select, which is something like this:
-Playstation
-- Playstation 5
--- Gry
--Playstation 3
--- Gry
Anyone can help me?
EDIT:
Problem solved by Build a tree from a flat array in PHP
This should work
usort($arr, function($a, $b) {
return $a["parent_id"] > $b["parent_id"];
});
Is there a way, with the two followings arrays to get another array which is the combination of those two arrays?
Array 1:
Array
(
[0] => Array
(
[a_id] => 9
[name] => Mario Lopez
)
[1] => Array
(
[a_id] => 8
[name] => Lisa Turtle
)
)
Array 2:
Array
(
[0] => Array
(
[b_id] => 1
[name] => AC Slater
)
[1] => Array
(
[b_id] => 2
[name] => Lisa Turtle
)
[2] => Array
(
[b_id] => 3
[name] => Kelly Kapowski
)
)
What I would like to get :
Array
(
[0] => Array
(
[b_id] => 1
[name] => AC Slater
)
[1] => Array
(
[a_id] => 8
[b_id] => 2
[name] => Lisa Turtle
)
[2] => Array
(
[b_id] => 3
[name] => Kelly Kapowski
)
[3] => Array
(
[a_id] => 9
[name] => Mario Lopez
)
)
The third array merges the two first arrays where the key name matches
I have not found a builtin function and tried this solution without success: combine 2 associative arrays where values match.
Thank you,
Edit: sorry, I forgot to add Mario Lopez.
My attempt was:
function array_extend($a, $b) {
foreach($b as $k=>$v) {
if( is_array($v) ) {
if( !isset($a[$k]) OR isset($v[0])) {
$a[$k] = $v;
} else {
$a[$k] = array_extend($a[$k], $v);
}
} else {
$a[$k] = $v;
}
}
return $a;
}
This probably is what you are looking for, although as #OldPadawan already pointed out in the comments to the question the actual result differs from the proposed one...
<?php
$a = [
[
'a_id' => 9,
'name' => 'Mario Lopez'
],
[
'a_id' => 8,
'name' => 'Lisa Turtle'
]
];
$b = [
[
'b_id' => 1,
'name' => 'AC Slater'
],
[
'b_id' => 2,
'name' => 'Lisa Turtle'
],
[
'b_id' => 3,
'name' => 'Kelly Kapowski'
]
];
$c = $a;
array_walk($b, function($be) use (&$c) {
$done = false;
array_walk($c, function(&$ce) use($be, &$done) {
if ($ce['name'] == $be['name']) {
$ce['b_id'] = $be['b_id'];
$done = true;
}
});
if ( ! $done) {
array_push($c, $be);
}
});
print_r($c);
The output of above code is:
Array
(
[0] => Array
(
[a_id] => 9
[name] => Mario Lopez
)
[1] => Array
(
[a_id] => 8
[name] => Lisa Turtle
[b_id] => 2
)
[2] => Array
(
[b_id] => 1
[name] => AC Slater
)
[3] => Array
(
[b_id] => 3
[name] => Kelly Kapowski
)
)
I have an array structure like this and wanted to Re-arrange it to the one below. Any suggestions for a faster/simple fix? I already did the addition of the dates. Thanks! :)
Input:
Array
(
[0] => Array
(
[user_id] => 255
[display_name] => Mark
[company_name] => Company_A
)
[1] => Array
(
[user_id] => 150
[display_name] => Paul
[company_name] => Company_A
)
[2] => Array
(
[user_id] => 25
[display_name] => Hulk
[company_name] => Company_B
)
[3] => Array
(
[user_id] => 50
[display_name] => Bob
[company_name] => Company_B
)
)
Output:
Array
(
[Company_A] => Array
(
[company_total_hours] => 20h 45m
[employees] => Array
(
[0] => Array
(
[user_id] => 255
[display_name] => Mark
)
[1] => Array
(
[user_id] => 150
[display_name] => Paul
)
)
)
[Company_B] => Array
(
[company_total_hours] => 7h 30m
[employees] => Array
(
[0] => Array
(
[user_id] => 25
[display_name] => Hulk
)
[1] => Array
(
[user_id] => 50
[display_name] => Bob
)
)
)
)
My Attempts:
<?php
$company_names = array();
foreach ($records as $k => $v) {
$company_names[] = $v->company_name;
}
$company_names = array_unique($company_names);
// hard coded testing
if (count($company_names) > 0) {
foreach($company_names as $k2 => $v2) {
$final_array[$v2]['company_total_hours'] = rand(1, 20);
$final_array[$v2]['employees'] = array(
array('user_id' => '255', 'display_name' => 'Mark'),
array('user_id' => '150', 'display_name' => 'Paul')
);
}
}
// on-going testing right now here....
I don't see where you derive your hours from so I left that out.
$i = 0;
foreach($vals as $keys => $arrays) {
if(!isset($new[$arrays['company_name']]))
$i = 0;
$new[$arrays['company_name']]['employees'][$i]['display_name'] = $arrays['display_name'];
$new[$arrays['company_name']]['employees'][$i]['user_id'] = $arrays['user_id'];
$i++;
}
Gives you:
Array
(
[Company_A] => Array
(
[employees] => Array
(
[0] => Array
(
[display_name] => Mark
[user_id] => 255
)
[1] => Array
(
[display_name] => Paul
[user_id] => 150
)
)
)
[Company_B] => Array
(
[employees] => Array
(
[0] => Array
(
[display_name] => Hulk
[user_id] => 25
)
[1] => Array
(
[display_name] => Bob
[user_id] => 50
)
)
)
)
foreach($arr as $v)
{
if(!$arr2[$v['company_name']]['employees'])
$arr2[$v['company_name']]['employees'] = array();
if(!$arr2[$v['company_name']]['company_total_hours'])
$arr2[$v['company_name']]['company_total_hours'] = '2h';//addional value
$arr2[$v['company_name']]['employees'][] = array('user_id'=>$v['user_id'],
'display_name'=>$v['display_name']
);
}
I have created a function which does the same thing as the answer given by #Rasclatt.
function groupByKeyValue($array, $oldKeyName, $newKeyName){
$newArray = array();
foreach($array as $key=>$value){
if(isset($newArray[$value[$oldKeyName]][$newKeyName])){
$newArray[$value[$oldKeyName]][$newKeyName][] = array('user_id'=> $value['user_id'], 'display_name' => $value['display_name']);
}else{
$newArray[$value[$oldKeyName]] = array($newKeyName => array(array('user_id'=> $value['user_id'], 'display_name' => $value['display_name'])));
}
}
return $newArray;
}
//usage
$newArray = groupByKeyValue($array, 'company_name', 'employees');
You can add a third parameter to send the keys for the array values which needs to be used in the new array for 'employees'. Please check this link for the working of the function http://goo.gl/I6Of5y
I need some clarity as to what PHP function can achieve what I'm aiming for.
This is a PHP array I have:
Array
(
[0] => Array
(
[id] => 6
[index] => 1
[active] => 1
[name] => MyName
)
[1] => Array
(
[id] => 1
[index] => 2
[active] => 1
[name] => YourName
)
[2] => Array
(
[id] => 2
[index] => 4
[active] => 1
[name] => TheirName
)
}
I want to take the "index" value and make it a KEY of that array parent, so the array would become this:
Array
(
[1] => Array
(
[id] => 6
[index] => 1
[active] => 1
[name] => MyName
)
[2] => Array
(
[id] => 1
[index] => 2
[active] => 1
[name] => YourName
)
[4] => Array
(
[id] => 2
[index] => 4
[active] => 1
[name] => TheirName
)
}
Can anyone please tell me how would I do this in PHP?
Thank you in advance.
you can use: array_column($array, null, 'index');
is the better solution, but only work for >= 5.5 php version
Not the most elegant solution, but it works (it doesn't actually move the array, it just generates a new one that corresponds to your requirements):
$resultArr = array();
foreach ($mainArr as $value) {
$resultArr[$value['index']] = $value;
}
unset($mainArr); // or $mainArr = $resultArr;
This way you won't overwrite any existing keys in your original array.
$a = array
(
0 => array
(
"id" => 6,
"index" => 1,
"active" => 1,
"name" => "MyName"
),
1 => Array
(
"id" => 1,
"index" => 2,
"active" => 1,
"name" => "YourName"
),
2 => Array
(
"id" => 2,
"index" => 4,
"active" => 1,
"name" => "TheirName"
)
);
$newArray = array();
foreach ($a as $foo) {
$newArray[$foo['index']] = $foo;
}
You have to do it manually with:
$input = array( /* your data */ );
$output = array();
foreach ( $input as $values ) {
$output[ $values['index'] ] = $values;
}
public static function normArray($key, $inputArray)
{
$outputArray = array();
foreach ($inputArray as $item) {
$index = intval($item[$key]);
$outputArray[$index] = $item;
}
return $outputArray;
}
I have array result like this:
Array
(
[0] => stdClass Object
(
[id_global_info] => 78
[name] => rfhd
[body] => dhfdhdf
[contact_author] => mirko
[date_created] => 2012-03-15 16:11:54
[date_expires] => 2012-04-14 16:11:54
[email] =>
[location_id] => 1
[category_id] => 26
[tag] => fhdhfdhfd
[info_type_id] => 4
[user_id] => 3
)
[1] => stdClass Object
(
[id_global_info] => 79
[name] => rfhd
[body] => dhfdhdf
[contact_author] => mirko
[date_created] => 2012-03-15 16:11:56
[date_expires] => 2012-04-14 16:11:56
[email] =>
[location_id] => 1
[category_id] => 26
[tag] => fhdhfdhfd
[info_type_id] => 4
[user_id] => 3
)
[2] => stdClass Object
(
[id_global_info] => 80
[name] => rfhd
[body] => dhfdhdf
[contact_author] => mirko
[date_created] => 2012-03-15 16:11:56
[date_expires] => 2012-04-14 16:11:56
[email] =>
[location_id] => 1
[category_id] => 26
[tag] => fhdhfdhfd
[info_type_id] => 4
[user_id] => 3
)
.
.
.
)
How can I search a multidimensional array and count number of results (for example I want to search for info_type_id with value of 4)?
Use array_filter to filter the array:
function test($arr) {
return $arr["info_type_id"] == 4;
}
echo count(array_filter($yourArray, "test"));
with foreach ?
function searchMyCoolArray($arrays, $key, $search) {
$count = 0;
foreach($arrays as $object) {
if(is_object($object)) {
$object = get_object_vars($object);
}
if(array_key_exists($key, $object) && $object[$key] == $search) $count++;
}
return $count;
}
echo searchMyCoolArray($input, 'info_type_id', 4);
You should try this :
$counter = 0;
$yourArray; // this var is your current array
foreach($yourArray as $object){
if($object->info_type_id == 4){
$counter++;
}
}