slice and merge 2 arrays - php

is there a good way to slice and merge 2 arrays based on empty values for example
first array
0 => string 'Perfect all gorgeous and arrived in less than 1 month for brazil' (length=64)
1 => string '' (length=0)
2 => string '' (length=0)
3 => string 'Good figures for their money, only instead of bits normal stick child bit rastroilsya' (length=85)
4 => string '' (length=0)
5 => string '' (length=0)
second array
0 => string '' (length=0)
1 => string 'http://g01.a.alicdn.com/kf/UTB8jjnecFfFXKJk43Otq6xIPFXaw.jpg" data-eid="eid-201782563197' (length=88)
2 => string 'http://g01.a.alicdn.com/kf/UTB87.bdcNHEXKJk43Jeq6yeeXXaZ.jpg" data-eid="eid-201782563197' (length=88)
3 => string '' (length=0)
4 => string 'http://g01.a.alicdn.com/kf/UTB8cxXwg4HEXKJk43Jeq6yeeXXam.jpg" data-eid="eid-201833045441' (length=88)
5 => string 'http://g04.a.alicdn.com/kf/UTB824Xwg4HEXKJk43Jeq6yeeXXaB.jpg" data-eid="eid-201833045441' (length=88)
I want them to be like this array
array (size=2)
0 =>
array (size=2)
'comment' => string 'Perfect all gorgeous and arrived in less than 1 month for brazil' (length=64)
'images' =>
array (size=2)
0 => string 'http://g01.a.alicdn.com/kf/UTB8jjnecFfFXKJk43Otq6xIPFXaw.jpg" data-eid="eid-201782563197' (length=88)
1 => string 'http://g01.a.alicdn.com/kf/UTB87.bdcNHEXKJk43Jeq6yeeXXaZ.jpg" data-eid="eid-201782563197' (length=88)
1 =>
array (size=2)
'comment' => string 'Good figures for their money, only instead of bits normal stick child bit rastroilsya' (length=85)
'images' =>
array (size=2)
3 => string 'http://g01.a.alicdn.com/kf/UTB8cxXwg4HEXKJk43Jeq6yeeXXam.jpg" data-eid="eid-201833045441' (length=88)
4 => string 'http://g04.a.alicdn.com/kf/UTB824Xwg4HEXKJk43Jeq6yeeXXaB.jpg" data-eid="eid-201833045441' (length=88)
How to do it ?

Got something that will help. It will work with more inputs if you need. It might not work best if your second array has more than one breaking blank. Just working on updated code to solve such issues.
<?php
$arr1 = array("input", "", "", "another input", "", "", "yet another input", "");
$arr2 = array("", "p1", "p2", "", "p01", "p02", "","p11" );
$inp = array("comment" => $arr1, "images" => $arr2);
function mangle_arrays($input) {
$out = array();
$gen = 0;
foreach($input as $key=>$val) {
$id = $gen?-1:0;
if ($gen) {
foreach($val as $v) {
if ($v) {
$out[$id][$key][] = $v;
} else {
$id++;
}
}
} else {
foreach($val as $v) {
if ($v) {
$out[$id] = array();
$out[$id][$key] = $v;
$id++;
}
}
}
$gen++;
}
return $out;
}
// your code goes here
echo "<pre>";
print_r(mangle_arrays($inp));
Results
Array
(
[0] => Array
(
[comment] => input
[images] => Array
(
[0] => p1
[1] => p2
)
)
[1] => Array
(
[comment] => another input
[images] => Array
(
[0] => p01
[1] => p02
)
)
[2] => Array
(
[comment] => yet another input
[images] => Array
(
[0] => p11
)
)
)

Related

Merge two array into one with the same key

I am trying to merge two array with the same key into one.
After i dump these variables
var_dump($allArtistsName);
var_dump($allTracksName);
I get this output
First array
array (size=3749)
0 => string 'Avicii' (length=6)
1 => string 'Arctic Monkeys' (length=14)
2 => string 'DJ Antoine' (length=10)
and second array
array (size=2135)
0 => string 'Hey Brother' (length=11)
1 => string 'Do I Wanna Know?' (length=16)
2 => string 'House Party - Airplay Edit' (length=26)
Basicly key 0 from first array matches with key 0 from second array.
So i am tryin go merge them somehow.
I have tried aarray_merge and array_merge_recursive
but i does not seem to work.
How i can solve this the best ?
EDIT:
My expected output would be something like
[
0 => [
'track' => 'Hey Brother',
'artists' => Avicii
1 => [
'track' => 'x',
'artists' => y
]
Several options:
$a = ['Avicii', 'Arctic Monkeys', 'DJ Antoine'];
$t = ['Hey Brother', 'Do I Wanna Know?', 'House Party - Airplay Edit'];
// option 1 - artist name as key, track as value
print_r(array_combine($a, $t));
// option 2 - artist name and track as subarray
print_r(array_map(null, $a, $t));
// option 3 - your expected output
$newArray = [];
foreach ($a as $key => $v) {
$newArray[] = [
'artist' => $v,
'track' => $t[$key],
];
}
You can use array_map thingie with a callback:
<?php
$artists = [
'Avicii',
'Arctic Monkeys',
'DJ Antoine',
];
$tracks = [
'Hey Brother',
'Do I Wanna Know?',
'House Party - Airplay Edit',
];
$merged = array_map(
function ($artist, $track) {
return ['artist' => $artist, 'track' => $track];
},
$artists,
$tracks
);
print_r($merged);
Output will be:
Array
(
[0] => Array
(
[artist] => Avicii
[track] => Hey Brother
)
[1] => Array
(
[artist] => Arctic Monkeys
[track] => Do I Wanna Know?
)
[2] => Array
(
[artist] => DJ Antoine
[track] => House Party - Airplay Edit
)
)

How to store a binary tree as one-dimensional array?

How to construct data into a binary tree sort to output a one-dimensional array?
Now that I have constructed the data into a binary tree, how can I recursively solve the binary tree as a one-dimensional array with the following code and data:
Data
$nodes = array(8,3,10,1,6,14,4,7,13);
Construct a binary tree code
function insertNode($node,$newNode){
//var_dump($node);
//var_dump($newNode);
//exit;
if ($node['key'] < $newNode['key']){
if (empty($node['right'])){
$node['right'] = $newNode;
}else{
$node['right'] = insertNode($node['right'],$newNode);
}
}elseif ($node['key'] > $newNode['key']){
if (empty($node['left'])){
$node['left'] = $newNode;
}else{
$node['left'] = insertNode($node['left'],$newNode);
}
}
return $node;
}
function tree($nodes)
{
$node = [
'key' => '',
'left' => '',
'right' => ''
];
$newNode = [
'key' => '',
'left' => '',
'right'=> ''
];
foreach ($nodes as $key => $value){
//insert($value,$key);
if($key == 0)
{
$node['key'] = $value;
continue;
}
$newNode['key'] = $value;
//Constructing a binary tree
$node = insertNode($node,$newNode);
}
//Recursive solution
$node = midSortNode($node);
return $node;
}
var_dump(tree($nodes));
The following is my constructed binary tree
array (size=3)
'key' => int 8
'left' =>
array (size=3)
'key' => int 3
'left' =>
array (size=3)
'key' => int 1
'left' => string '' (length=0)
'right' => string '' (length=0)
'right' =>
array (size=3)
'key' => int 6
'left' =>
array (size=3)
...
'right' =>
array (size=3)
...
'right' =>
array (size=3)
'key' => int 10
'left' => string '' (length=0)
'right' =>
array (size=3)
'key' => int 14
'left' =>
array (size=3)
...
'right' => string '' (length=0)
I need to recursively classify the binary tree into a well-ordered one-dimensional array.
My code is as follows
function midSortNode($node){
$sortArr = [];
if (!empty($node)){
$sortArr[] = midSortNode($node['left']);
//$sortArr['left'] = midSortNode($node['left']);
array_push($sortArr,$node['key']);
$sortArr[] = midSortNode($node['right']);
//$sortArr['right'] = midSortNode($node['right']);
}
return $sortArr;
}
var_dump(midSortNode($node));
Here is the result, but not what I want
0 =>
array (size=3)
0 =>
array (size=3)
0 =>
array (size=0)
...
1 => int 1
2 =>
array (size=0)
...
1 => int 3
2 =>
array (size=3)
0 =>
array (size=3)
...
1 => int 6
2 =>
array (size=3)
...
1 => int 8
2 =>
array (size=3)
0 =>
array (size=0)
empty
1 => int 10
2 =>
array (size=3)
0 =>
array (size=3)
...
1 => int 14
2 =>
array (size=0)
...
How to solve the binary tree as follows
array (size=9)
0 => int 1
1 => int 3
2 => int 4
3 => int 6
4 => int 7
5 => int 8
6 => int 10
7 => int 13
8 => int 14
I'm assuming that your happy with the steps so far, so the main code as it is isn't changed. All I think you need to do is to extract the data from the final tree into a 1 dimensional array. As the items are all leaf nodes and in order, you can just use array_walk_recursive() to go over all of the nodes and add them to a new array...
$tree = tree($nodes);
array_walk_recursive( $tree,
function ($data) use (&$output) { $output[] = $data;} );
print_r($output);
gives...
Array
(
[0] => 1
[1] => 3
[2] => 4
[3] => 6
[4] => 7
[5] => 8
[6] => 10
[7] => 13
[8] => 14
)
Edit:
To update the existing code to do this, you can change the midSortNode() to pass around the list of outputs and only add in the current node...
function midSortNode($node, $sortArr = []){
if (!empty($node)){
$sortArr = midSortNode($node['left'], $sortArr);
$sortArr[] = $node['key'];
$sortArr = midSortNode($node['right'], $sortArr);
}
return $sortArr;
}

how to replace or eliminate #xsi::nill => true in php multi dimensional arrays

I have a php array like this
print_r(myarray) is
Array ( [0] => Array ( [#xsi:nil] => true ) [1] => Array ( [#xsi:nil] => true ) [2] => Array ( [#xsi:nil] => true ) [3] => 'some value' [4] => Array ( [#xsi:nil] => true ))
I need to eliminate the values Array ( [#xsi:nil] => true ) or just to replace them with say "nill". I tried a lot, this being a nested array i couldnt get the key for the values [#xsi:nil] => true
How to check in php for the indexes which hold the value Array ( [#xsi:nil] => true )? and replace them with say 'nill'?
trial one :
$key1 = array_search(array('#xsi:nil'=>'true'), array_column($arrays, 'NOTE')); //to catch the indexes.
function searchMyCoolArray($arrays, $key, $search) {
$count = 0;
foreach($arrays as $object) {
if(is_object($object)) {
$ob1 = $object;
$object = get_object_vars($object);
$key1 = array_search(40489, array_column($arrays, 'uid'));
}
if(array_key_exists($key, $object) && $object[$key] == $search)
{
// print_r($first_names_note[$key]);
// echo "ffgfg ".$ob1[0]." rtrtrt";
// var_dump($object);
// print_r($arrays[$key]);
// echo $object;
// print_r($object);
// print_r($first_names_note)."<br>";
$count++;
//echo "sddsdsdsd";
}
}
return $count;
}
echo searchMyCoolArray($first_names_note, '#xsi:nil', 'true');
here i got the count correct, but it was not i need, I tried to get the indexs in the function itself, but failed
Please help, i googled alot pleeeeeeeeeeeeeeeeez
You may try to use array_walk to traverse the array and then unset all elements with the key #xsi:nil like this:
<?php
$arr = array(
array("#xsi:nil" => true),
array("#xsi:nil" => true),
array("#xsi:nil" => true),
array("some_value" =>4),
array("#xsi:nil" => true),
);
array_walk($arr, function(&$data){
if(is_array($data) && array_key_exists("#xsi:nil", $data)){
unset($data["#xsi:nil"]);
$data[] = "nil";
}
});
var_dump($arr);
// IF YOU WANT TO REMOVE ALL EMPTY ARRAYS COMPLETELY, JUST DO THIS:
$arr = array_filter($arr);
var_dump($arr);
// GET THE LENGTH OF THE FILTERED ARRAY.
$count = count($arr);
echo $count; //<== PRODUCES 5
// THE 1ST VAR_DUMP() PRODUCES:
array (size=5)
0 =>
array (size=1)
0 => string 'nil' (length=3)
1 =>
array (size=1)
0 => string 'nil' (length=3)
2 =>
array (size=1)
0 => string 'nil' (length=3)
3 =>
array (size=1)
'some_value' => int 4
4 =>
array (size=1)
0 => string 'nil' (length=3)
// THE 2ND VAR_DUMP() PRODUCES:
array (size=5)
0 =>
array (size=1)
0 => string 'nil' (length=3)
1 =>
array (size=1)
0 => string 'nil' (length=3)
2 =>
array (size=1)
0 => string 'nil' (length=3)
3 =>
array (size=1)
'some_value' => int 4
4 =>
array (size=1)
0 => string 'nil' (length=3)
Test it out HERE.
Cheers & Good Luck...
This is not the answer, the code for the answer was provided by #Poiz
Here is my complete code which i formatted
//my array
$arr = Array (Array ( '#xsi:nil' => 'true' ), Array ('#xsi:nil' => 'true' ), Array ( '#xsi:nil' => 'true' ) );
// print_r($arr);
//performed array walk
array_walk($arr, function(&$data){
if(is_array($data) && array_key_exists("#xsi:nil", $data)){
unset($data["#xsi:nil"]);
$data = "nil";
}
});
print_r($arr);
//OUTPUT : Array ( [0] => nil [1] => nil [2] => nil )

Reorganizing a PHP array structure (arrays within arrays)

I have this array within array which contains a lot of values:
183 =>
array (size=3)
0 => string 'DE' (length=2)
1 => string '2015-06-09' (length=10)
2 => string 'GK' (length=2)
184 =>
array (size=3)
0 => string 'DE' (length=2)
1 => string '2015-06-08' (length=10)
2 => string 'GL' (length=2)
185 =>
array (size=3)
0 => string 'FR' (length=2)
1 => string '2015-06-09' (length=10)
2 => string 'GN' (length=2)
186 =>
array (size=3)
0 => string 'FR' (length=2)
1 => string '2015-09-08' (length=10)
2 => string 'GO' (length=2)
0 is the country code. 1 is a date. 2 is a column on an Excel file.
I want to organize it in this way:
2015-06-09 =>
array (size=3)
DE =>
array (size=2)
column => GK
download => 666
FR =>
array (size=2)
column => GN
download => 777
2015-06-08 =>
array (size=3)
DE =>
array (size=2)
column => GL
download => 666
FR =>
array (size=2)
column => GO
download => 777
So the same date can show up more than once. if it gets to an array value with the same date - it inserts in it the country code with and its' column.
if it has more than 1 country - it adds a new country. (with the 'download' and column values).
I have this function:
function get_cols_to_array_by_date($array) {
$mainarr = array();
$last_in_arr = count($array);
for ($i=0; $i<$last_in_arr; $i++){
$mainarr[$array[$i][1]] = array( $array[$i][0]=> array('downloads'=> 666, 'col'=>$array[$i][2]) );
}
return $mainarr;
}
which outputs an array that runs over the country when it gets to the same date and doesn't give me an array of countries.
What part am I missing in my code?
Is there a simpler way to do it? ( PHP syntax shortcuts ;) )
Assuming that the downloads is the key of the initial array, and each element has 3 elements(date and 2 countries):
Code:
//demo array
$old = array(
555=>array(
0 => 'DE',
1 => '2015-06-09',
2 => 'GK'),
234=>array(
0 => 'DE',
1 => '2015-06-08',
2 => 'GL'),
123=>array(
0 => 'FR',
1 => '2015-06-09',
2 => 'GN')
);
$new = array();
foreach($old as $key=>$arrayValues)
{
if(!array_key_exists($arrayValues[1], $new)){ //check if there is already a key by date
$new[$arrayValues[1]] = array();
}
$new[$arrayValues[1]][$arrayValues[0]] = array('column'=>$arrayValues[2], 'downloads'=>$key); //append formated array
}
echo "<pre>";
var_dump($new);
echo "</pre>";
Output:
array(2) {
["2015-06-09"]=>
array(2) {
["DE"]=>
array(2) {
["column"]=>
string(2) "GK"
["downloads"]=>
int(555)
}
["FR"]=>
array(2) {
["column"]=>
string(2) "GN"
["downloads"]=>
int(123)
}
}
["2015-06-08"]=>
array(1) {
["DE"]=>
array(2) {
["column"]=>
string(2) "GL"
["downloads"]=>
int(234)
}
}
}
Try looping and checking if element exists, if not - add it.
$result = [];
foreach ($myArray as $key => $values) {
if (!isset($result[$values[1]])) {
$result[$values[1]] = [
$values[0] => [
'column' => $values[2],
'download' => $key,
]
];
} elseif (!isset($result[$values[1]][$values[0]])) {
$result[$values[1]][$values[0]] = [
'column' => $values[2],
'download' => $key,
];
}
}
Sandbox

Array Combine Question in PHP

HI,
I got two array.
var_dump($tbDateArr);
var_dump($tbTitleArr);
output:
array
0 =>
object(stdClass)[16]
public 'eventDate' => string '5' (length=1)
1 =>
object(stdClass)[17]
public 'eventDate' => string '16' (length=2)
array
0 =>
object(stdClass)[18]
public 'eventTitle' => string 'mar' (length=10)
1 =>
object(stdClass)[19]
public 'eventTitle' => string 'tri' (length=10)
BTW,I print them as this,
print_r($tbDateArr);
echo '<br>';
print_r($tbTitleArr);
Array ( [0] => stdClass Object ( [eventDate] => 5 ) [1] => stdClass Object ( [eventDate] => 16 ) )
Array ( [0] => stdClass Object ( [eventTitle] => mar ) [1] => stdClass Object ( [eventTitle] => tri ) )
I tried to combin them,
$dataArr = array_combine($tbDateArr, $tbTitleArr);
I JUST WANT THE SIMPLY RESULT as this,
Array
(
[5] => mar
[16] => tri
)
Is there anything wrong? Appreciated for your help.
[updated with array_merge]
array
0 =>
object(stdClass)[16]
public 'eventDate' => string '5' (length=1)
1 =>
object(stdClass)[17]
public 'eventDate' => string '16' (length=2)
2 =>
object(stdClass)[18]
public 'eventTitle' => string 'fuzhou mar' (length=10)
3 =>
object(stdClass)[19]
public 'eventTitle' => string 'weihai tri' (length=10)
Assuming that $tbDateArr and $tbTitleArr entries only have a single property (eventDate and eventTitle respectively), you can do this:
$array = array_combine(
array_map('current', $tbDateArr),
array_map('current', $tbTitleArr)
);
If they have (or can have) more than a single property, you're better off using a good old foreach, assuming they have matching keys (if they don't, just array_values them beforehand):
$array = array();
foreach ($tbDateArr as $key => $value) {
$array[$value] = $tbTableArr[$key];
}
You can't directly combine the arrays, since the values you need are stored as properties in objects -- you have to pull these values out and use them:
$keys = array_map('getEventDate', $tbDateArr);
$values = array_map('getEventDate', $tbTitleArr);
print_r(array_combine($keys, $values));
function getEventDate($o) {
return $o->eventDate;
}
EDIT
this works
$arr1 = array(
"5",
"16",
);
$arr2 = array(
"mar",
"tri",
);
$result = array_combine($arr1, $arr2);
print_r($result);
You are trying to combine arrays which containing objects. array_combine using its first argument for keys second argument as values.

Categories