How to merge 2 outputs array in PHP - php

I'm a beginer in PHP programming, i want to ask for my problem here.
Before, i get the PHP scripts from: https://github.com/VosCast/SHOUTcast-PHP-Stats
This is the code, how i get the array:
require_once 'vc_shoutcast.class.php'; // get stats
require_once 'vc_shoutcast_json_relay.class.php'; // produce json
$lists = array(
array(
'host' => 'host.net',
'port' => '9898'
),
array(
'host' => 'host.net',
'port' => '8787'
)
);
$i = 1;
foreach ($lists as $list => $radio) {
$vc_shoutcast = new vc_shoutcast( $radio['host'], $radio['port'], false );
$vc_shoutcast_json_relay = new vc_shoutcast_json_relay( $vc_shoutcast, 1, $cache = './stats_' . $i . '.json' );
$vc_shoutcast_json_relay->run( 'both' );
$i++;
}
This is the vc_shoutcast_json_relay.class.php ( $vc_shoutcast_json_relay->run( 'both' ); ) code:
foreach ($vars as $value) {
$data[$value] = $this->vc_shoutcast->$value;
}
var_dump( $data );
From the code above, I'll get two outputs array, like this:
Array(
[currentlisteners] => 2,
[maxlisteners] => 3,
[songtitle] => Some song title 2
)
Array(
[currentlisteners] => 12,
[maxlisteners] => 13,
[songtitle] => Some song title 2
)
How do I merge two arrays into one array become:
Array(
[0] => (
[currentlisteners] => 2,
[maxlisteners] => 3,
[songtitle] => Some song title 2
),
[1] => (
[currentlisteners] => 12,
[maxlisteners] => 13,
[songtitle] => Some song title 2
)
)
I know, i can merge 2 arrays with array_merge( $data ) or with something similiar functions, but it isn't works.
Thanks for your help.

Simplest way is to just create a new one with your existing arrays as the values:
$newArray = array($array1, $array2);
This is the same as this:
$newArray = array();
array_push($newArray, $array1);
array_push($newArray, $array2);
Or this:
$newArray = array();
$newArray[] = $array1;
$newArray[] = $array2;
Depending on your code, you might prefer to add your data to the main array using one of the last two methods as you go along, rather than trying to create the whole thing in one go at the end.

Related

arrays with dif keys inside 1 array

like the question says, I have 2 foreach cycles, 1 cycle iterates an array with 4 keys, and the other one an array with 3 keys, how to get this two arrays in only 1 ?
I have this
....
],
],
'Detalle' => array()
];
foreach ($datos["line_items"] as $line => $item) {
$tempArray = array(
'NmbItem' => $item['name'],
'QtyItem' => $item['quantity'],
'PrcItem' => $item['price'],
'IndExe' => 1
);
}
foreach($datos["fee_lines"] as $line => $fee){
$tempArray=array(
'NmbItem' => $fee['name'],
'QtyItem' => 1,
'PrcItem' => $fee['total']
);
}
$dte['Detalle'][] = $tempArray;
}
if you notice the second array cycle doesnt contain 'indexe' key, after asign this tempArray in $dte['Detalle'][] = $tempArray only works with the last cycle, or the first one if I remove the second.
the output should be something like:
temp = Array (
array[0]
'NmbItem => name',
'QtyItem'=> 10,
'PrcItem'= 1000,
'IndExe' => 1
array[1]
'NmbItem => another name',
'QtyItem'=> 5,
'PrcItem'=> 3000
)
To make it work with your code, you should also add $dte['Detalle'][] = $tempArray; after the first loop.
The issue is that you are setting the $tempArray in each foreach so you end up with only the last one when assigning it in the $dte['Detalle'].
So, something like this should work:
foreach ($datos["line_items"] as $line => $item) {
$tempArray = array(
'NmbItem' => $item['name'],
'QtyItem' => $item['quantity'],
'PrcItem' => $item['price'],
'IndExe' => 1
);
}
$dte['Detalle'][] = $tempArray;
foreach($datos["fee_lines"] as $line => $fee){
$tempArray=array(
'NmbItem' => $fee['name'],
'QtyItem' => 1,
'PrcItem' => $fee['total']
);
}
$dte['Detalle'][] = $tempArray;
However, I would do it using the array_map function.
Docs for array_map
You can have it something like this:
<?php
$data_1 = array_map(function($item){
return array(
'NmbItem' => $item['name'],
'QtyItem' => $item['quantity'],
'PrcItem' => $item['price'],
'IndExe' => 1
);
}, $datos["line_items"]);
$data_2 = array_map(function($fee){
return array(
'NmbItem' => $fee['name'],
'QtyItem' => 1,
'PrcItem' => $fee['total']
)
}, $datos["fee_lines"]);
$dte['Detalle'] = array_merge($dte['Detalle'], $data_1, $data_2);

PHP insert index as value in array

How can I add to a multidimensional array also the index number of the current added item?
$data_array[] = array('data_array_index' => *the index number of the this array on $data_array*, 'stuff' => 'stuff', etc.)
So when I:
print_r($data_array);
Array(
[0] => Array(
data_array_index => 0
stuff => stuff
)
[25] => Array(
data_array_index => 25
stuff => stuff
)
etc.
Thank you
EDIT
Should this work?
$data_array[] = array('data_array_index' => end($data_array)+1, 'stuff' => 'stuff', etc.)
You could do this:
$array = [
0 => [ "data_array_index" => 0, "stuff" => "stuff" ],
25 => [ "data_array_index" => 25, "stuff" => "stuff" ]
];
$array[] = array('data_array_index' => 0, 'stuff' => 'stuff')
end($array);
$last_id = key($array);
$array[$last_id]['data_array_index'] = $last_id;
I don't know why you want data_array_index in the array because if you put it in a foreach loop you can get the key without needing the variable.
Example:
foreach($key => $data) {
^^^^ The same as `data_array_index`
}
Suppose you have this array:
$data_array = [
0 => [ "data_array_index" => 0, "stuff" => "stuff" ],
25 => [ "data_array_index" => 25, "stuff" => "stuff" ]
];
Now to set a key (note the $data_array[100]):
$data_array[100] = [ "data_array_index" => 100, "stuff" => "stuff" ];
try this once
$arr=array(12=>array("stuff"=>"stuff1"),15=>array("stuff"=>"stuff2"));
foreach($arr as $key=>$val){
$arr[$key]['data_array_index']=$key;
}
echo "<pre>"; print_r($arr);
For my solution see the code below. Beware that this is a very rudimentary function now. It does not provide any fail safe or fallback. If you delete a key it will to fill the space etc.
<?php
// data array
$data_array = [];
// additional info for the array
$info_a = "Lorem Ipsum";
$info_b = "Lorem Ipsum";
// call function
addElement($data_array, $info_a);
addElement($data_array, $info_b);
// display output
echo '<pre>';
print_r($data_array);
echo '</pre>';
function addElement(&$array, $info)
{
// add info to the array
$array[] = [
'stuff'=>$info
];
// get the key of the current array
end($array);
$key = key($array);
// add this information to the array
$array[$key]['data_array_index'] = $key;
}
?>
Output would be
Array
(
[0] => Array
(
[stuff] => Lorem Ipsum
[data_array_index] => 0
)
[1] => Array
(
[stuff] => Lorem Ipsum
[data_array_index] => 1
)
)
Use array_walk
array_walk($data_array,function($value,$key)use($new_array) {
$value['data_array_index'] = $key;
$new_array[$key]=$value;
});
working demo: http://phpfiddle.org/main/code/p937-7cue

How do I reform this array into a differently structured array

I have an array that looks like this:
[0] => Array
(
[name] => typeOfMusic
[value] => this_music_choice
)
[1] => Array
(
[name] => myMusicChoice
[value] => 9
)
[2] => Array
(
[name] => myMusicChoice
[value] => 8
)
I would like to reform this into something with roughly the following structure:
Array(
"typeOfMusic" => "this_music_choice",
"myMusicChoice" => array(9, 8)
)
I have written the following but it doesn't work:
foreach($originalArray as $key => $value) {
if( !empty($return[$value["name"]]) ){
$return[$value["name"]][] = $value["value"];
} else {
$return[$value["name"]] = $value["value"];
}
}
return $return;
I've tried lots of different combinations to try and get this working. My original array could contain several sets of keys that need converting to arrays (i.e. it's not always going to be just "myMusicChoice" that needs converting to an array) ?
I'm getting nowhere with this and would appreciate a little help. Many thanks.
You just need to loop over the data and create a new array with the name/value. If you see a repeat name, then change the value into an array.
Something like this:
$return = array();
foreach($originalArray as $data){
if(!isset($return[$data['name']])){
// This is the first time we've seen this name,
// it's not in $return, so let's add it
$return[$data['name']] = $data['value'];
}
elseif(!is_array($return[$data['name']])){
// We've seen this key before, but it's not already an array
// let's convert it to an array
$return[$data['name']] = array($return[$data['name']], $data['value']);
}
else{
// We've seen this key before, so let's just add to the array
$return[$data['name']][] = $data['value'];
}
}
DEMO: https://eval.in/173852
Here's a clean solution, which uses array_reduce
$a = [
[
'name' => 'typeOfMusic',
'value' => 'this_music_choice'
],
[
'name' => 'myMusicChoice',
'value' => 9
],
[
'name' => 'myMusicChoice',
'value' => 8
]
];
$r = array_reduce($a, function(&$array, $item){
// Has this key been initialized yet?
if (empty($array[$item['name']])) {
$array[$item['name']] = [];
}
$array[$item['name']][] = $item['value'];
return $array;
}, []);
$arr = array(
0 => array(
'name' => 'typeOfMusic',
'value' => 'this_music_choice'
),
1 => array(
'name' => 'myMusicChoice',
'value' => 9
),
2 => array(
'name' => 'myMusicChoice',
'value' => 8
)
);
$newArr = array();
$name = 'name';
$value = 'value';
$x = 0;
foreach($arr as $row) {
if ($x == 0) {
$newArr[$row[$$name]] = $row[$$value];
} else {
if (! is_array($newArr[$row[$$name]])) {
$newArr[$row[$$name]] = array();
}
array_push($newArr[$row[$$name]], $row[$$value]);
}
$x++;
}

PHP: how to create associative array by key?

I have simple array
array(
array( 'id'=>5, 'something' => 2, 'dsadsa' => 'fsfsd )
array( 'id'=>20, 'something' => 2, 'dsadsa' => 'fsfsd )
array( 'id'=>30, 'something' => 2, 'dsadsa' => 'fsfsd )
)
How to create associative array by id field (or something else) from it in the right way?
array(
'5' => array( 'something' => 2, 'dsadsa' => 'fsfsd )
'20' => array( 'something' => 2, 'dsadsa' => 'fsfsd )
'30' => array( 'something' => 2, 'dsadsa' => 'fsfsd )
)
Something along these lines.
$new_array = array();
foreach ($original_array as &$slice)
{
$id = (string) $slice['id'];
unset($slice['id']);
$new_array[$id] = $slice;
}
#NikitaKuhta, nope. There is no slice function which returns a column of values in a 2D keyed table associated with a given key or column heading. You can use some of the callback array_... functions, but you will still need to execute a custom function per element so its just not worth it. I don't like Core Xii's solution as this corrupts the original array as a side effect. I suggest that you don't use references here:
$new_array = array();
foreach ($original_array as $slice) {
$id = (string) $slice['id'];
unset($slice['id']);
$new_array[$id] = $slice;
}
# And now you don't need the missing unset( $slice)

Matching an array value by key in PHP

I have an array of items:
array(
[0] => array(
'item_no' => 1
'item_name' => 'foo
)
[1] => array(
'item_no' => 2
'item_name' => 'bar'
)
) etc. etc.
I am getting another array from a third party source and need to remove items that are not in my first array.
array(
[0] => array(
'item_no' => 1
)
[1] => array(
'item_no' => 100
) # should be removed as not in 1st array
How would I search the first array using each item in the second array like (in pseudo code):
if 'item_no' == x is in 1st array continue else remove it from 2nd array.
// Returns the item_no of an element
function get_item_no($arr) { return $arr['item_no']; }
// Arrays of the form "item_no => position in the array"
$myKeys = array_flip(array_map('get_item_no', $myArray));
$theirKeys = array_flip(array_map('get_item_no', $theirArray));
// the part of $theirKeys that has an item_no that's also in $myKeys
$validKeys = array_key_intersect($theirKeys, $myKeys);
// Array of the form "position in the array => item_no"
$validPos = array_flip($validKeys);
// The part of $theirArray that matches the positions in $validPos
$keptData = array_key_intersect($theirArray, $validPos);
// Reindex the remaining values from 0 to count() - 1
return array_values($keptData);
All of this would be easier if, instead of storing the key in the elements, you stored it as the array key (that is, you'd be using arrays of the form "item_no => item_data") :
// That's all there is to it
return array_key_intersect($theirArray, $myArray);
You can also do:
$my_array =array(
0 => array( 'item_no' => 1,'item_name' => 'foo'),
1 => array( 'item_no' => 2,'item_name' => 'bar')
);
$thrid_party_array = array(
0 => array( 'item_no' => 1),
1 => array( 'item_no' => 100),
);
$temp = array(); // create a temp array to hold just the item_no
foreach($my_array as $key => $val) {
$temp[] = $val['item_no'];
}
// now delete those entries which are not in temp array.
foreach($thrid_party_array as $key => $val) {
if(!in_array($val['item_no'],$temp)) {
unset($thrid_party_array[$key]);
}
}
Working link
If your key is not actually a key of your array but a value, you will probably need to do a linear search:
foreach ($itemsToRemove as $itemToRemove) {
foreach ($availableItems as $key => $availableItem) {
if ($itemToRemove['item_no'] === $availableItem['item_no']) {
unset($availableItems[$key]);
}
}
}
It would certainly be easier if item_no is also the key of the array items like:
$availableItems = array(
123 => array(
'item_no' => 123,
'item_name' => 'foo'
),
456 => array(
'item_no' => 456,
'item_name' => 'bar'
)
);
With this you could use a single foreach and delete the items by their keys:
foreach ($itemsToRemove as $itemToRemove) {
unset($availableItems[$itemToRemove['item_no']]);
}
You could use the following to build an mapping of item_no to your actual array keys:
$map = array();
foreach ($availableItems as $key => $availableItem) {
$map[$availableItems['item_no']] = $key;
}
Then you can use the following to use the mapping to delete the corresponding array item:
foreach ($itemsToRemove as $itemToRemove) {
unset($availableItems[$map[$itemToRemove['item_no']]]);
}

Categories