Values from multidimensional to array - php

array fetched somewhere else:
Array
(
[0] => Array
(
[id] => 600000
[name] => test1
)
[1] => Array
(
[id] => 600300
[name] => test2
)
[2] => Array
(
[id] => 600600
[name] => test3
)
)
php:
$leftnav = array("root_id" => 0, "sub_id" => 0, "subsub_id" => 0, "subsubsub_id" => 0);
if (isset($category_data[0]['id']))
$leftnav['root_id'] = $category_data[0]['id'];
if (isset($category_data[1]['id']))
$leftnav['sub_id'] = $category_data[1]['id'];
if (isset($category_data[2]['id']))
$leftnav['subsub_id'] = $category_data[2]['id'];
if (isset($category_data[3]['id']))
$leftnav['subsubsub_id'] = $category_data[3]['id'];
Can the php code be done in a more pretty way? I have tried with array_map but all required keys in $leftnav will not be set.

$i = 0;
foreach( $leftnav as $k => $v ) {
if ( isset($category_data[$i]['id']) ) {
$leftnav[$k] = $category_data[$i]['id'];
}
$i++;
}

Related

Compare different arrays structures

I have two arrays with different structures. Array 1 and Array 2 that I will name from MyList and MyFiles. I would get to return only MyList values that do not have in MyFiles. But the two arrays have different structures and I'm having trouble trying to compare
MyList
Array
(
[info] => Array
(
[0] => Array
(
[player] => Messi
[week] => Array
(
[id] => 252
[videos] => Array
(
[0] => Array
(
[id] => 2929850
[link] => goals.mp4
)
[1] => Array
(
[id] => 2929848
[link] => best.mp4
)
[2] => Array
(
[id] => 2929847
[link] => dribbling.mp4
)
)
)
)
[1] => Array
(
[player] => CR7
[week] => Array
(
[id] => 251
[videos] => Array
(
[0] => Array
(
[id] => 2929796
[link] => goals.mp4
)
[1] => Array
(
[id] => 2929795
[link] => best.mp4
)
)
)
)
[2] => Array
(
[player] => Neymar
[week] => Array
(
[id] => 253
[videos] => Array
(
[0] => Array
(
[id] => 2929794
[link] => goals.mp4
)
[1] => Array
(
[id] => 2929793
[link] => best.mp4
)
)
)
)
)
)
MyFiles Array
Array
(
[252] => Array
(
[0] => Array
(
[id] => 2929850
[link] => goals.mp4
)
[1] => Array
(
[id] => 2929848
[link] => best.mp4
)
)
[251] => Array
(
[0] => Array
(
[id] => 2929796
[link] => goals.mp4
)
[1] => Array
(
[id] => 2929795
[link] => best.mp4
)
)
)
the comparison must be made by id of the week and id of the video
I tried this but it did not work out:
$new = array();
foreach ($list['info'] as $source) {
foreach ($source["week"]['videos'] as $keys => $videos) {
foreach ($file as $key => $upload) {
if ($source["week"]["id"] == $key ) {
for($i=0; $i<count($source["week"]["videos"]); $i++){
if($videos["id"] == $upload[$i]["id"]){
unset($videos);
}else{
$new[] = $videos;
}
}
} else {
$new[] = $videos;
}
}
}
}
The expected return would be something like this.
Array
(
[info] => Array
(
[0] => Array
(
[player] => Messi
[week] => Array
(
[id] => 252
[videos] => Array
(
[2] => Array
(
[id] => 2929847
[link] => dribbling.mp4
)
)
)
)
[2] => Array
(
[player] => Neymar
[week] => Array
(
[id] => 253
[videos] => Array
(
[0] => Array
(
[id] => 2929794
[link] => goals.mp4
)
[1] => Array
(
[id] => 2929793
[link] => best.mp4
)
)
)
)
)
)
I have hidden the array in a usable format for my sake in the future should this answer be incorrect and need changing.
$desired = array();
$desired['info'][0]['player'] = 'Messi';
$desired['info'][0]['week']['id'] = 252;
$desired['info'][0]['week']['videos'][2]['id'] = 2929847;
$desired['info'][0]['week']['videos'][2]['link'] = 'dribbling.mp4';
$desired['info'][2]['player'] = 'Neymar';
$desired['info'][2]['week']['id'] = 253;
$desired['info'][2]['week']['videos'][0]['id'] = 2929794;
$desired['info'][2]['week']['videos'][0]['link'] = 'goals.mp4';
$desired['info'][2]['week']['videos'][1]['id'] = 2929793;
$desired['info'][2]['week']['videos'][1]['link'] = 'best.mp4';
$list = array();
$list["info"][0]["player"] = "Messi";
$list["info"][0]["week"]["id"] = "252";
$list["info"][0]["week"]["videos"][0]["id"] = 2929850;
$list["info"][0]["week"]["videos"][0]["link"] = "goals.mp4";
$list["info"][0]["week"]["videos"][1]["id"] = 2929848;
$list["info"][0]["week"]["videos"][1]["link"] = "best.mp4";
$list["info"][0]["week"]["videos"][2]["id"] = 2929847;
$list["info"][0]["week"]["videos"][2]["link"] = "dribbling.mp4";
$list["info"][1]["player"] = "CR7";
$list["info"][1]["week"]["id"] = "251";
$list["info"][1]["week"]["videos"][0]["id"] = 2929796;
$list["info"][1]["week"]["videos"][0]["link"] = "goals.mp4";
$list["info"][1]["week"]["videos"][1]["id"] = 2929795;
$list["info"][1]["week"]["videos"][1]["link"] = "best.mp4";
$list["info"][2]["player"] = "Neymar";
$list["info"][2]["week"]["id"] = "253";
$list["info"][2]["week"]["videos"][0]["id"] = 2929794;
$list["info"][2]["week"]["videos"][0]["link"] = "goals.mp4";
$list["info"][2]["week"]["videos"][1]["id"] = 2929793;
$list["info"][2]["week"]["videos"][1]["link"] = "best.mp4";
$file = array();
$file[252][0]['id'] = 2929850;
$file[252][0]['link'] = 'goals.mp4';
$file[252][1]['id'] = 2929848;
$file[252][1]['link'] = 'best.mp4';
$file[251][0]['id'] = 2929796;
$file[251][0]['link'] = 'goals.mp4';
$file[251][1]['id'] = 2929795;
$file[251][1]['link'] = 'best.mp4';
Edit
function array_diff_assoc_recursive($array1, $array2) {
$difference=array();
foreach ($array1 as $key => $value) {
if (is_array($value)) {
if( !isset($array2[$key]) || !is_array($array2[$key])) {
$difference[$key] = $value;
} else {
$new_diff = array_diff_assoc_recursive($value, $array2[$key]);
if (!empty($new_diff))
$difference[$key] = $new_diff;
}
} else if (!array_key_exists($key,$array2) || $array2[$key] !== $value) {
$difference[$key] = $value;
}
}
return $difference;
}
$new = array('info' => array());
foreach ($list['info'] as $key => $item) {
$a = $item['week']['videos'];
//$b = $file[$item['week']['id']] ?? []; // This is PHP7+
$b = isset($file[$item['week']['id']]) ? $file[$item['week']['id']] : [];
$c = array_diff_assoc_recursive($a, $b);
if (!empty($c)) {
$new['info'][$key] = $item;
$new['info'][$key]['week']['videos'] = $c;
}
}
You will need a function that will check the difference between the videos arrays.
What I do is simply iterate over the list array and then check the difference between that item and the file array. The difference is then stored in $c.
If there is a difference then if statement is fired which will store that player in the $new array and then replace the videos array with the difference array.
This is similar to what you were doing when you were unsetting variables.

foreach loop to extract and group sub-arrays

Array:
Array
(
[0] => Array
(
[date] => 2018-05-23
[content] => Array
(
[0] => Array
(
[0] => AAAAAA
[1] => BBBBBB
[2] => CCCCCC
[3] => DDDDDD
[4] => EEEEEE
[5] => FFFFFF
[6] => GGGGGG
[7] => HHHHHH
[8] => IIIIII
[9] => JJJJJJ
)
)
)
[1] => Array
(
[date] => 2018-05-22
[content] => Array
(
[0] => Array
(
[0] => KKKKKK
[1] => LLLLLL
[2] => MMMMMM
[3] => NNNNNN
...
I need to be able to create a foreach loop that will create a database record from 3 variables.
foreach #1:
$date = $array['content']['date']; //2018-05-23
$headline = $array['content'][0][$key]; // AAAAAA
$content = $array['content'][0][$key]; // BBBBBB
foreach #2:
$date = $array['content']['date']; //2018-05-23
$headline = $array['content'][0][$key]; // CCCCCC
$content = $array['content'][0][$key]; // DDDDDD
Until it finishes with the first sub-array and then goes to the second array:
foreach #6:
$date = $array['content']['date']; //2018-05-22
$headline = $array['content'][0][$key]; // KKKKKK
$content = $array['content'][0][$key]; // LLLLLL
I've been trying to group the arrays with array_chunk with no success and then I tried to write a small fix to order the array properly with this:
if ($x <= 10) {
if ( $a < 2 ) {
$a++;
} else {
$x++;
$a = 1;
}
$res[$i]['content'][$x][] = ltrim($text);
} else {
$res[$i]['content'][$x][] = ltrim($text);
$x = 0;
}
Result:
[date] => 2018-05-23
[content] => Array
(
[0] => Array
(
[0] => AAAAAA
[1] => BBBBBB
)
[1] => Array
(
[0] => CCCCCC
[1] => DDDDDD
)
[2] => Array
(
[0] => EEEEEE
[1] => FFFFFF
)
[3] => Array
(
[0] => GGGGGG
[1] => HHHHHH
)
Which worked for the first array but all the other arrays lost order and were not categorized properly.
Any ideas how this can be created?
EDIT: content will always have 24 records (0-23), so if divided into chunks we should get 12 array chunks for every content sub-array.
I'm not sure how your DB structure looks like because you didn't mention, but you can do something like that:
<?php
$array = [
[
"date" => "date",
"content" => [["A", "B", "C"]]
],
[
"date" => "date",
"content" => [["E", "F", "G", "H"]]
],
];
$sql = "INSERT INTO table (content, date) VALUES ";
foreach ($array as $key => $item) {
$content = $item["content"][0];
for ($i = 0; $i < count($content); $i += 2) {
$letters = $content[$i];
if (isset($content[$i + 1])) {
$letters .= $content[$i + 1];
}
$sql .= "('$letters', '$item[date]'),";
}
}
$sql = rtrim($sql, ",") . ";";
echo $sql;
Will output:
INSERT INTO table (content, date) VALUES ('AB', 'date'),('C', 'date'),('EF', 'date'),('GH', 'date');
<?php
$collection =
array
(
array
(
'date' => '2018-05-23',
'content' => array
(
array
(
'AAAAAA',
'BBBBBB',
'CCCCCC',
'DDDDDD',
'EEEEEE',
'FFFFFF',
'GGGGGG',
'HHHHHH',
'IIIIII',
'JJJJJJ'
)
)
),
array
(
'date' => '2018-05-22',
'content' => array
(
array
(
'KKKKKK',
'LLLLLL',
'MMMMMM',
'NNNNNN'
)
)
)
);
function getChunks($data){
$result = array();
$length = count($data);
for($i=0;$i<$length;$i += 2){
$result[] = array($data[$i],$data[$i+1]);
}
return $result;
}
function groupContentByDate($collection){
$result = array();
foreach($collection as $each_data){
$result[$each_data['date']] = array('content' => array());
foreach($each_data['content'] as $each_content){
$result[$each_data['date']]['content'] = array_merge($result[$each_data['date']]['content'],getChunks($each_content));
}
}
return $result;
}
echo "<pre>";
print_r(groupContentByDate($collection));
OUTPUT
Array
(
[2018-05-23] => Array
(
[content] => Array
(
[0] => Array
(
[0] => AAAAAA
[1] => BBBBBB
)
[1] => Array
(
[0] => CCCCCC
[1] => DDDDDD
)
[2] => Array
(
[0] => EEEEEE
[1] => FFFFFF
)
[3] => Array
(
[0] => GGGGGG
[1] => HHHHHH
)
[4] => Array
(
[0] => IIIIII
[1] => JJJJJJ
)
)
)
[2018-05-22] => Array
(
[content] => Array
(
[0] => Array
(
[0] => KKKKKK
[1] => LLLLLL
)
[1] => Array
(
[0] => MMMMMM
[1] => NNNNNN
)
)
)
)

PHP Array re-arrange to Multi Dimensional

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

Create 2 dimensional array from 1 dimensional

How from this array:
Array
(
[0] => Array
(
[BLACK] => Array
(
[0] => 3171
[1] => 3173
[2] => 3175
)
[WHITE] => Array
(
[0] => 3170
[1] => 3172
[2] => 3174
)
)
[1] => Array
(
[SMALL] => Array
(
[0] => 3170
[1] => 3171
)
[MEDIUM] => Array
(
[0] => 3172
[1] => 3173
)
[LARGE] => Array
(
[0] => 3174
[1] => 3175
)
)
)
I could create something like this:
$array['BLACK']['SMALL'] = 3171;
$array['BLACK']['MEDIUM'] = 3173;
$array['BLACK']['LARGE'] = 3175;
$array['WHITE']['SMALL'] = 3170;
$array['WHITE']['MEDIUM'] = 3172;
$array['WHITE']['LARGE'] = 3174;
so create 2 dimensional array from 1 dimensional, where option is same.
<?php
$colors = array('BLACK' => array('3171','3173','3175'),'WHITE' => array('3170','3172','3174'));
$sizes = array('SMALL' => array('3170','3171'),'MEDIUM' => array('3172','3173'), 'LARGE' => array('3174','3175'));
$merged = array();
foreach ($colors as $c_key => $color) {
foreach ($color as $c_val) {
foreach ($sizes as $s_key => $size) {
foreach ($size as $s_val) {
if ($c_val == $s_val) {
$merged[$c_key][$s_key] = $c_val;
}
}
}
}
}
// var_dump($merged);
?>

array manipulation and rearranging

Here's my deal.
I have this array:
Array // called $data in my code
(
[0] => Array
(
[name] => quantity
[value] => 0
)
[1] => Array
(
[name] => var_id
[value] => 4
)
[2] => Array
(
[name] => quantity
[value] => 0
)
[3] => Array
(
[name] => var_id
[value] => 5
)
)
which I need it to be like:
Array // called $temp in my code
(
[0] => Array
(
[0] => Array
(
[name] => quantity
[value] => 0
)
[1] => Array
(
[name] => var_id
[value] => 4
)
)
[2] => Array
(
[0] => Array
(
[name] => quantity
[value] => 0
)
[1] => Array
(
[name] => var_id
[value] => 5
)
)
)
and I did it using this code I made:
$data = $_POST['data'];
$temp = array();
foreach($data as $key => $datum)
{
if($key%2 == 0)
{
$temp[$key] = array();
array_push($temp[$key], $datum, $data[$key+1]);
}
}
But I think that my code is some kinda stupid, specially if I have a huge data.
eventually what I want to do is just have each two indexes combined in one array, and I know that there should be something better than my code to do it, any suggestions?
Discover array_chunk()
$temp = array_chunk($data, 2);
$cnt = count($data);
$temp = array();
for ($i = 0; $i < $cnt; $i = $i + 2)
{
$temp[] = array($data[$i], $data[$i+1]);
}
Take a look at array_chunk.
<?php
$array = array(
array(1),
array(2),
array(3),
array(4),
);
print_r(
array_chunk($array, 2, false)
);
/*
Array
(
[0] => Array
(
[0] => Array
(
[0] => 1
)
[1] => Array
(
[0] => 2
)
)
[1] => Array
(
[0] => Array
(
[0] => 3
)
[1] => Array
(
[0] => 4
)
)
)
*/

Categories