Inserting shifted array back into multidimensional array - php

So far I have a multidimen array results
foreach ($votes as $vote) {
$choices = array();
Foreach ($vote->getVoteChoicesOrdered() as $choice) {
array_push($choices, $choice->getAnswer()->getID());
}
array_push($results, $choices);
}
Later, I want to remove the first element of each choice in results and shift the positions back up (so I can remove the next element at [0] if I need to)
foreach ($results as $res) {
if (in_array(array_values($res)[0], $losers)) {
$shiftedRes = array_shift($res);
}
}
$losers is an array of array keys
Now that I have the shifted array, how would i go about replacing the current $result element with the new $shiftedRes? Something like $results[key($res)] = $shiftedRes?

Instead of shifting from your $res array, do it directly from the $results array.
foreach (array_keys($results) as $key)
{
if (in_array(array_values($results[$key])[0], $losers))
{
$shiftedRes = array_shift($results[$key]);
}
}

Related

PHP Creating an indexed array vs associative array

I am calling the getTeams function below to get a simple list of team names but I can't get it to work without a 2 step process.
If I use
function getTeams($teams){
foreach ($teams as $team) {
$team = $team['team'];
$teamNames[] = $team['displayName'];
}
return $teamNames;
}
It looks like it is creating an associative array with the keys being numeric starting at 0?
I can make it work using
function getTeams($teams){
foreach ($teams as $team) {
$team = $team['team'];
$teamNames[] = $team['displayName'];
}
for ($i= 0; $i < count($teamNames); $i++){
$teamNames2[$teamNames[$i]]=$teamNames[$i];
}
return $teamNames2;
}
I think it might be because the first array is an associative Array and the second one is creating an indexed array? Is that thought process correct? If so, what is the correct way to create an indexed array in the foreach loop?
Without knowing your array: If you want to create an associative array you should give its element a key. So instead of
function getTeams($teams){
foreach ($teams as $team) {
$team = $team['team'];
$teamNames[] = $team['displayName'];
}
return $teamNames;
}
where the code
$teamNames[]
will add always an indexed entry to your array.
If you want a associative entry use a key instead. Something like
function getTeams($teams){
foreach ($teams as $team) {
$team = $team['team'];
$teamNames[$team['key']] = $team['displayName'];
}
return $teamNames;
}
$teamNames should now return an associative array

Get only specific key/values from JSON by key names not all

I have JSON that shows multiple key-value pairs. I'd like to loop through and create a new array with only the key-value pairs I want in order to display them. This is my attempt, but of course, my code is re-writing my array ($new_array) to have only one element.
//SAMPLE JSON
[{"PropertyId":"555","FloorplanId":"555","FloorplanName":"Studio","Beds":"0","Baths":"1.00","AvailabilityURL","UnitTypeMapping":".058500"},{"PropertyId":"666","FloorplanId":"666","FloorplanName":"Studio","Beds":"0","Baths":"1.00","AvailabilityURL","UnitTypeMapping":".058500"}]
//GET ALL JSON FROM URL
$json = file_get_contents('<URL>');
$data = json_decode($json);
// print_r($data); //ALL keys
//GET JUST THE KEYS I WANT
$new_array = array("FloorplanName"=>"","Beds"=>"","Baths"=>"");
// Create new array
foreach($data as $item) {
$new_array['FloorplanName'] = $item->{'FloorplanName'};
$new_array['Beds'] = $item->{'Beds'};
$new_array['Baths'] = $item->{'Baths'};
}
//loop over $new_array
foreach($new_array as $item) {
$item->{'FloorplanName'};
$item->{'Beds'};
$item->{'Baths'};
}
Right now, you set associative keys on $new_array and overwrite your data each time through your foreach loop. Instead, you need to add an item (a sub-array) to $new_array and assign the data to the sub-array.
Instead of this:
//GET JUST THE KEYS I WANT
$new_array = array("FloorplanName"=>"","Beds"=>"","Baths"=>"");
// access property of object in array
foreach($data as $item) {
$new_array['FloorplanName'] = $item->{'FloorplanName'};
$new_array['Beds'] = $item->{'Beds'};
$new_array['Baths'] = $item->{'Baths'};
}
You need
$new_array = array(); // this array should be empty
// access property of object in array
foreach($data as $item) {
$new_array[] = array(
'FloorplanName' => $item->{'FloorplanName'},
'Beds' => $item->{'Beds'},
'Baths' => $item->{'Baths'},
);
}
Also, to loop through the new array, you need to change your final loop:
//loop over $new_array
foreach($new_array as $item) {
echo $item['FloorplanName'];
echo $item['Beds'];
echo $item['Baths'];
}

How to create an empty 2d array and assign values to it in PHP?

I have created an empty 2d array:
multiArray = array(array());
I wanted to add items to the 2d array using a foreach statement, such that for each item, add all the items of a second array that correlate to it. This would build my 2d array. I am going about it as such:
# The following variables are prepopulated with items
# $array1, my first array of items
# $array2, my second array of items
foreach ($array1 as $item1) {
foreach ($array2 as $item2) {
if ($item2['marker'] === $item1['marker'] { //item2 belongs to item 1 and thus needs to be added to the 2d array
$mulitArray[][] = [$item1][$item2];
}
}
}
That is not working though logically it seems sounds, but the PHP doesn't like that $mulitArray[][] = [$item1][$item2].
My expected output would be a 2d array that would show for each item1, all the item2s that match.
Thanks in advanced.
Maybe something like this.
$multiArray = array();
foreach ($array1 as $item1) {
$a = array();
foreach ($array2 as $item2) {
if ($item1['marker'] == $item2['marker']) {
$a[] = $item2;
}
}
$multiArray[] = $a;
}

Pushing key/value pairs to an array, loses key out of forloop

I get my data from the database, but want to add 2 keys to them. So I add them in a for loop. If I dump (simple function that prints the array with pre tags) the single result in the for loop, it's correct, when I dump the 2dimensional array outside of it, it doesn't have the keys anymore..
For some reason it doesn't push it to the 2dimensional array?
$results is a 2dimensional array btw.
//add amount and subtotal to the array's elements
foreach ($results as $result) {
$result['amount'] = $sessionShoppingCart[$result['artikelnummer']][1];
$result['subtotal'] = $result['amount'] * $result['Verkoopprijs'];
$this->dump($result);
}
$this->dump($results);
To change an array within the foreach you can do two things.
Reference the array value with &:
foreach ($results as &$result) {
Or use the key and modify the array:
foreach ($results as $key => $result) {
$results[$key]['amount'] = $sessionShoppingCart[$result['artikelnummer']][1];
$results[$key]['subtotal'] = $result['amount'] * $result['Verkoopprijs'];
}

PHP removing elements from array in a foreach loop

I'm trying to unset() some elements from an array but when using a foreach loop to go through 1 array to delete these elements from another array it does not seems to be working.
if (isset($this->request->post['merge'])) {
$merge_orders = $this->request->post['merge'];
}
$selected_order = min($merge_orders); // Fetch the max value order_id
unset($merge_orders[$selected_order]); // Take it out of the array.
$orders_list = explode(',', $this->request->post['order_id_list']);
$removeKeys = $merge_orders;
foreach($removeKeys as $key) {
unset($orders_list[$key]);
echo $key;
}
echo print_r($orders_list);
The first unset works fine but the second does not, the array is set and properly formatted but it still does not seem to remove the elements from the $orders_list array.
If you only use one parameter on a foreach loop you are delivered the value of the occurance and not the key for the occurance.
Try this so that you are getting a key from the foreach loop and not a value
foreach($removeKeys as $key => $val) {
unset($orders_list[$key]);
echo $key;
}

Categories