how to generate multidimensional array from array value - php

i'm new in php and i stuck some where actually i need to generate multidimensional array from array value.
e.g my array is like that and remember all array and value are dynamic
array(
0 => array(
0 => "college"
1 => "student"
2 => "contact"
),
1 => array(
0 => "college"
1 => "parents"
2 => "contact"
),
2 => array(
0 => "school"
1 => "parents"
2 => "contact"
),
3 => array(
0 => "school"
1 => "student"
2 => "contact"
))
and i want result like that
0 => array (
"college" => array(
"student" => array (
"contact" => array (
"address" => "address_value"
)
),
"parents" => array (
"contact" => array (
"address" => "address_value"
)
),
),
"school" => array(
"student" => array (
"contact" => array (
"address" => "address_value"
)
),
"parents" => array (
"contact" => array (
"address" => "address_value"
)
),
)),
i want to generate multidimensional array till the array value and last array has some value
can any one help me with standard way.
help will appreciated..
thanks in advance

Try this:
<?php
function group($a, $level, $previous = '') {
$b = [];
for( $i = 0, $n = count($a); $i < $n; ++$i ) {
if( $level > 0 && $a[$i][$level-1] !== $previous ) {
continue;
}
$key = $a[$i][$level];
$b[$key] = [];
if( array_key_exists($level+1, $a[$i]) ) {
$b[$key] = group($a, $level+1, $key);
}
}
return $b;
}
print_r(group($a, 0));
Output:
Array(
[college] => Array (
[student] => Array (
[contact] => Array ()
)
[parents] => Array (
[contact] => Array ()
)
)
[school] => Array (
[student] => Array (
[contact] => Array ()
)
[parents] => Array (
[contact] => Array ()
)
)
)
Using #AlivetoDie example:
Array (
[college] => Array (
[student] => Array (
[contact] => Array ()
)
[parents] => Array (
[contact] => Array ()
)
)
[school] => Array (
[parents] => Array (
[contact] => Array ()
)
[student] => Array (
[contact] => Array ()
)
[data] => Array (
[contact] => Array()
)
)
)

Related

PHP - How To Grouping if value same in array

This my array example
Array
(
[0] => Array ( [_id] => 5f76b1788ee23077dccd1a2c [product] => Array ( [0] => Array ( [_id] => 5d0391a4a72ffe76b8fcc610 ) ) [count] => 1 )
[1] => Array ( [_id] => 5f76b6288ee2300700cd1a3a [product] => Array ( [0] => Array ( [_id] => 5d0391b6a72ffe76b8fcc611 ) ) [count] => 1 )
[2] => Array ( [_id] => 5f76d2488ee23083d3cd1a4a [product] => Array ( [0] => Array ( [_id] => 5d0391b6a72ffe76b8fcc611 ) ) [count] => 1)
)
And i want to group if product value same, like this,
Array
(
[0] => Array ( [_id] => 5f76b1788ee23077dccd1a2c [product] => Array ( [0] => Array ( [_id] => 5d0391a4a72ffe76b8fcc610 ) ) [count] => 1 )
[1] => Array ( [_id] => 5f76b6288ee2300700cd1a3a [product] => Array ( [0] => Array ( [_id] => 5d0391b6a72ffe76b8fcc611 ) ) [count] => 2 )
)
It makes no sense to retain the first level ids since you are arbitrarily trashing some of the first level ids (damaging the relationships) during the merging process.
Instead I recommend that you only isolate the data that is accurately related.
If this output does not serve your needs, then I'll ask for further question clarification.
By assigning temporary keys to your output array, the output array also acts as a lookup array by which you can swiftly check for uniqueness. The "null coalescing operator" (??) sets a fallback value of 0 when an id is encountered for the first time -- this prevents generating any warnings regarding undeclared keys.
Code: (Demo)
$array = [
['_id' => '5f76b1788ee23077dccd1a2c', 'product' => ['_id'=>'5d0391a4a72ffe76b8fcc610'], 'count'=> 1],
['_id' => '5f76b6288ee2300700cd1a3a', 'product' => ['_id'=>'5d0391b6a72ffe76b8fcc611'], 'count'=> 1],
['_id' => '5f76d2488ee23083d3cd1a4a', 'product' => ['_id'=>'5d0391b6a72ffe76b8fcc611'], 'count'=> 1]
];
$productCounts = [];
foreach ($array as $item) {
$productId = $item['product']['_id'];
$productCounts[$productId] = ($productCounts[$productId] ?? 0) + $item['count'];
}
var_export($productCounts);
Output:
array (
'5d0391a4a72ffe76b8fcc610' => 1,
'5d0391b6a72ffe76b8fcc611' => 2,
)
If you insist of the desired output in your question, then it can be as simple and efficient as this...
Code: (Demo)
$result = [];
foreach ($array as $item) {
$productId = $item['product']['_id'];
if (!isset($result[$productId])) {
$result[$productId] = $item;
} else {
$result[$productId]['count'] += $item['count'];
}
}
var_export(array_values($result));
Output:
array (
0 =>
array (
'_id' => '5f76b1788ee23077dccd1a2c',
'product' =>
array (
'_id' => '5d0391a4a72ffe76b8fcc610',
),
'count' => 1,
),
1 =>
array (
'_id' => '5f76b6288ee2300700cd1a3a',
'product' =>
array (
'_id' => '5d0391b6a72ffe76b8fcc611',
),
'count' => 2,
),
)
You can try the below code it will work for you :-)
<?php
$Myarray = array(['_id'=> '5f76b1788ee23077dccd1a2c', 'product'=> ['_id'=>'5d0391a4a72ffe76b8fcc610'] ,'count'=> 1 ],
['_id'=> '5f76b6288ee2300700cd1a3a', 'product'=> ['_id'=>'5d0391b6a72ffe76b8fcc611'] ,'count'=> 1 ],
['_id'=> '5f76d2488ee23083d3cd1a4a', 'product'=> ['_id'=>'5d0391b6a72ffe76b8fcc611'] ,'count'=> 1 ]
);
$user_array = [];
$temp_array = [];
foreach($Myarray as $temp)
{
$found = array_search($temp['product']['_id'], $temp_array);
if($found !== false)
{
$i = 0;
foreach($user_array as $temp1)
{
if($temp1['product']['_id'] == $temp['product']['_id'])
{
$sum = $temp1['count'] + 1;
$user_array[$i]['count'] = $sum;
}
$i++;
}
}
else
{
array_push($user_array,$temp);
array_push($temp_array,$temp['product']['_id']);
}
}
print_r($user_array);
?>
This will produce below Output
Array ( [0] => Array ( [_id] => 5f76b1788ee23077dccd1a2c [product] => Array ( [_id] => 5d0391a4a72ffe76b8fcc610 ) [count] => 1 ) [1] => Array ( [_id] => 5f76b6288ee2300700cd1a3a [product] => Array ( [_id] => 5d0391b6a72ffe76b8fcc611 ) [count] => 2 ) )

change a key of a single element array

I have an array tree from a database, I want to change the key of a child element in this case the second array 'eric'=>array into integer '0'=>array as follow :
0 => Array
('text' => 'paris',
'nodes' => Array
('eric' => Array
( 'text' => 'eric',
'nodes' => Array
(0 => Array
(
'text' => 'so.png',
),
),
),
),
),
there is my code :
while($d = mysqli_fetch_assoc($result)) {
if(!isset($data[$d['country']])) {
$data[$d['country']] = array(
'text' => $d['country'],
'nodes' => array()
);
}
if(!isset($data[$d['country']]['nodes'][$d['name']])) {
$data[$d['country']]['nodes'][$d['name']] = array(
'text' => $d['name'],
'nodes' => array()
);
}
array_push($data[$d['country']]['nodes'][$d['name']]['nodes'], $d['n_doc']);
}
To change all of the child keys to numeric values, you can simply just use array_values()
Live Demo
for($i = 0; $i <= count($data) -1; $i++) { # This loops through each country
$data[$i]['nodes'] = array_map(function($node) { # This preserves the parent text value
return array_values($node); # [0] => Paris, [1] => array(...)
}, $data[$i]['nodes']);
}
Output
[ ... => [ text => Paris, nodes => [ 0 => Paris, 1 => [ ... ] ] ... ] ... ]
can you change your code for this input:
Array
(
[0] => Array
(
[text] => paris
[nodes] => Array
(
[jacque] => Array
(
[text] => jacque
[nodes] => Array
(
[0] => 32.png
)
)
[anis] => Array
(
[text] => anis
[nodes] => Array
(
[0] => 5384a97ee9d6b (2).pd
)
)
)
)
[1] => Array
(
[text] => london
[nodes] => Array
(
[dodo] => Array
(
[text] => dodo
[nodes] => Array
(
[0] => 148782.svg
[1] => 333.png
)
)
[sd] => Array
(
[text] => sd
[nodes] => Array
(
[0] => 1014-favicon.ico
)
)
)
)
)

Searching in a multidimensional array

I've an array:
Array
(
[_edit_lock] => Array
(
[0] => 1434971582:11
)
[_edit_last] => Array
(
[0] => 11
)
[_wp_page_template] => Array
(
[0] => page-templates/langenfeldDreiSpalterMitSiderbarsRL.php
)
[_wpas_done_all] => Array
(
[0] => 1
)
[hefo_before] => Array
(
[0] => 0
)
[hefo_after] => Array
(
[0] => 0
)
[sharing_disabled] => Array
(
[0] => 1
)
[spacious_page_layout] => Array
(
[0] => left_sidebar
)
[_thumbnail_id] => Array
(
[0] => 2641
)
[ort] => Array
(
[0] => langenfeld
)
)
I want to save the "ort" in a variable.
[ort] => Array
(
[0] => langenfeld
)
My code give me the values of the array but how can I save the values?
My code:
foreach ($gpc as $k){
foreach ($k as $v){
//echo $v;
}
}
I thought something like that:
$ort = $v['ort'];
But that's not working for me. Can someone help?
This code is working properly
$arr = Array
(
'_edit_lock' => Array
(
'0' => "1434971582:11",
),
'_edit_last' => Array
(
'0' => "11",
),
'_wp_page_template' => Array
(
'0' => "page-templates/langenfeldDreiSpalterMitSiderbarsRL.php",
),
'_wpas_done_all' => Array
(
'0' => "1",
),
'hefo_before' => Array
(
'0' => "0",
),
'hefo_after' => Array
(
'0' => "0",
),
'sharing_disabled' => Array
(
'0' => "1",
),
'spacious_page_layout' => Array
(
'0' => "left_sidebar",
),
'_thumbnail_id' => Array
(
'0' => "2641",
),
'ort' => Array
(
'0' => "langenfeld",
),
);
$ort = $arr["ort"];
print_r($ort);
// output
Array
(
[0] => langenfeld
)
if you directly want langenfeld
$ort = $arr['ort'][0];
//this will output - langenfeld

Count occurrences of a value inside a multidimensional array

so i retrieve a json, convert it into an array and i got this output:
Array
(
[Sid] => 23888555
[pages] => Array
(
[0] => Array
(
[id] => 13111071
[name] => Page 1
[slots] => Array
(
[0] => Array
(
[SlotId] => 6
[info] => Array
(
[id] => 5247
[color] => red
)
)
[1] => Array
(
[SlotId] => 4
[info] => Array
(
[id] => 5267
[color] => blue
)
)
[2] => Array
(
[SlotId] => 7
[info] => Array
(
[id] => 5267
[color] => green
)
)
)
)
[1] => Array
(
[id] => 13111072
[name] => Page 2
[slots] => Array
(
[0] => Array
(
[SlotId] => 6
[info] => Array
(
[id] => 5247
[color] => red
)
)
[1] => Array
(
[SlotId] => 4
[info] => Array
(
[id] => 5267
[color] => blue
)
)
)
)
)
)
I have no problem reading it whatsoever, what i wanna do is count for every page how many similar "last" id i got.
Exemple :
[pages][0][slots][0][info][id]
[pages][0][slots][1][info][id]
[pages][0][slots][3][info][id]
For the page 1, I wanna compare these 3 ids between them and count the occurrences.
[pages][1][slots][0][info][id]
[pages][1][slots][1][info][id]
For the page 2, I wanna compare these 2 ids between them and count the occurrences.
The output i want looks like this :
page 1 -> 1x5247
-> 2x5267
page 2 -> 1x5247
-> 1x5267
EDIT :
I tried using
foreach ($data['pages'] as $item) {
foreach ($item['slots'] as $slotnumber => $value) {
print_r(array_count_values($item['slots'][$slotnumber]['info']));
}
}
which returns me this :
Array ( [5247] => 1 [red] => 1 )
Array ( [5267] => 1 [blue] => 1 )
Array ( [5267] => 1 [green] => 1 )
So i think i might be able to use this but i don't know how.
I manually declared the array and then created the countstuff() function. This should work for you. I tested it and it work on my end. After going through all this trouble, I really do appreciated it if you choose my answer and up vote it.
<?php
$data = Array("Sid" => "23888555", "pages" => Array("0" => Array("id" => "13111071", "name" => "Page 1", "slots" => Array("0" => Array("SlotId" => "6", "info" => Array("id" => "5247", "color" => "red")), "1" => Array("SlotId" => "4", "info" => Array("id" => "5267", "color" => "blue")), "2" => Array("SlotId" => "7","info" => Array("id" => "5267", "color" => "green")))),
"1" => Array
(
"id" => "13111072",
"name" => "Page 2",
"slots" => Array
(
"0" => Array
(
"SlotId" => "6",
"info" => Array
(
"id" => "5247",
"color" => "red"
)
),
"1" => Array
(
"SlotId" => "4",
"info" => Array
(
"id" => "5267",
"color" => "blue"
)
)
)
)
)
);
//End of array declaration
//Now the really convoluted coding starts
//Create a function
function countstuff($yourarray){
foreach($yourarray as $mainarraykey => $mainarray){
if($mainarraykey == "pages"){
foreach($mainarray as $pageskey => $pagesarray){
//echo "Page \"$pageskey\"<br/>";
foreach($pagesarray as $pagessubarraykey => $pagessubarray_array){
if($pagessubarraykey == "slots"){
foreach($pagessubarray_array as $slotskey => $slots){
foreach($slots as $slotssubkey => $slotssub){
if($slotssubkey == "info"){
foreach($slotssub as $key => $value){
if($key == "id"){
//echo $value."<br/>";
$pages[$pageskey][] = $value;
}
}
}
}
}
}
}
}
}
}
return $pages;
}
//Execute the countstuff() function
$output = countstuff($data);
function showresults($input){
foreach($input as $pagekey => $page){
echo "Page $pagekey:<br/>";
$results = array_count_values($page);
foreach($results as $resultkey => $result){
echo $result."x".$resultkey."<br/>";
}
echo "<br/>";
}
}
showresults($output);
?>
I tried some things let me know what you guys think of this.
I get every id then enter them into an array then use array_count_values
$array_ids = array();
foreach ($data['pages'] as $item) {
$numberOfElements = count($item['slots']);
$z= 0;
foreach ($item['slots'] as $slotnumber => $value) {
$array_ids[$z] = $item['slots'][$slotnumber]['info']['id'];
// search for occurrences when the array is full
if (count($array_ids) == $numberOfElements) {
var_dump(array_count_values($array_ids));
// reset the array to 0 every time we loop through the whole infos
$array_ids = array();
}
$z++;
}
}
This seems to work for every page.
array (size=2)
5267 => int 2
5247 => int 1
array (size=2)
5267 => int 1
5247 => int 1

How can I remove duplicates in an array like this?

How can i remove duplicates in an array like this?
My array $test1 gives me this out:
Array (
[0] => Array ( [id] => 47523 [date] => 12-02-13 14:36:32 )
[1] => Array ( [id] => 47523 [date] => 12-02-13 13:56:48 )
[2] => Array ( [id] => 38639 [date] => 12-02-13 13:38:51 )
[3] => Array ( [id] => 38639 [date] => 12-02-13 13:07:43 )
)
My array $test2 gives me this out:
Array (
[0] => Array ( [id] => 47523 [date] => 12-02-13 14:36:32 )
[1] => Array ( [id] => 47523 [date] => 12-02-13 13:56:48 )
[2] => Array ( [id] => 38639 [date] => 12-02-13 13:38:51 )
[3] => Array ( [id] => 38639 [date] => 12-02-13 13:07:43 )
[4] => Array ( [id] => 53241 [date] => 12-02-13 11:02:48 )
)
But I want the output to be that way with the latest date
Array (
[0] => Array ( [id] => 53241 [date] => 03-02-13 11:02:48 )
)
What can i do?
$test1 = array (
array ( "id" => 47523, "date" => "12-02-13 14:36:32" ),
array ( "id" => 47523, "date" => "12-02-13 13:56:48" ),
array ( "id" => 38639, "date" => "12-02-13 13:38:51" ),
array ( "id" => 38639, "date" => "12-02-13 13:07:43" )
);
$test2 = array (
array ( "id" => 47523, "date" => "12-02-13 14:36:32" ),
array ( "id" => 47523, "date" => "12-02-13 13:56:48" ),
array ( "id" => 38639, "date" => "12-02-13 13:38:51" ),
array ( "id" => 38639, "date" => "12-02-13 13:07:43" ),
array ( "id" => 53241, "date" => "12-02-13 11:02:48" )
);
foreach($test2 as $array) {
if (!in_array($array, $test1)) {
$new[] = $array;
}
}
print_r($new);
First merge the 2 arrays (from $test2 into $tes1 in this case):
foreach($test2 as $id=>$arr){
$test1[] = $arr;
}
Then sort the $test1 by date (putting the oldest dates last, and newest dates first):
foreach ($test1 as $key => $row) {
$orderByDate[$key] = strtotime($row['date']);
}
array_multisort($orderByDate, SORT_DESC, $dataArray);
Then remove the duplicates (This will keep the newest datetime and remove earlier ones)
$unique = array()
foreach($test1 as $id => $arr){
if( in_array($arr->id, $unique ) {
unset($test1[$id]);
}
else {
array_push($unique, $arr->id);
}
}
Try using array_unique($test1)
You can use array_intersect_key with array_unique and array_map for single line job:
In PHP >5.3.0:
$array = array (
0 => array ( "id" => 47523, "date" => "12-02-13 14:36:32" ),
1 => array ( "id" => 47523, "date" => "12-02-13 13:56:48" ),
2 => array ( "id" => 38639, "date" => "12-02-13 13:38:51" ),
3 => array ( "id" => 38639, "date" => "12-02-13 13:07:43" )
);
$array = array_intersect_key($array, array_unique(array_map(function($n){ return $n['id']; }, $array)));
print_r($array);
PHP <5.3.0
$array = array (
0 => array ( "id" => 47523, "date" => "12-02-13 14:36:32" ),
1 => array ( "id" => 47523, "date" => "12-02-13 13:56:48" ),
2 => array ( "id" => 38639, "date" => "12-02-13 13:38:51" ),
3 => array ( "id" => 38639, "date" => "12-02-13 13:07:43" )
);
function mapArray($n){
return $n['id'];
}
$array = array_intersect_key($array, array_unique(array_map("mapArray", $array)));
print_r($array);
You should write your own function beacuse array_unique is not for multidimensional arrays.
function array_unique_md($array)
{
$temp = array();
foreach($array as $key => $value)
{
if(!isset($temp[$value['id']])) $temp[$value['id']] = $value['date'];
}
$your_structure = array();
foreach($temp as $key=> $value)
{
$your_structure[] = array('id'=>$key,'date'=>$value);
}
return $your_structure;
}
You can use array_reduce
$data = array_reduce($data, function($a,$b){
isset($a[$b['id']]) or $a[$b['id']] = $b;
return $a;
});
var_dump(array_values($data));
See Live Demo

Categories