Php array rebuild - php

I got an array looking like this:
array("canv" => array(1 => "4", 2 => "6", 3 => "9", 4 => "7");
I need it to look like this:
array("canv" => array("4", "6", "9", "7");
so I can easly check if the value exist this way:
if(isset($result["canv"][$gid])) where $gid is a number from "4", "6", "9", "7".
How can it be done?

This will flip the values to become keys and vice versa:
$result["canv"] = array_flip($result["canv"]);
So instead of
array(1 => "4", 2 => "6", 3 => "9", 4 => "7")
you'll have
array("4" => 1, "6" => 2, "9" => 3, "7" => 4)
But then again think about building the original array in the desired way and only do this if you can't afford that.

It won't work because you are looking for array keys, while 4, 6, 9 and 7 are the values, but if you use array_search($gid, $result['canv']) you'll find the index of $gid or false if $gid's value is not in the list.
So this will work:
if(array_search($gid, $result['canv']) !== false){
//Do Stuff
}

Without any modification, with your existing array, you can check it as:
if (in_array($gid, $result["canv"])) {
// $gid is in the array
}
Logically, if canv is to be an array of those values, the values should be array members rather than the array keys which point to members. You are asking to use them as array keys. Unless you want them to behave as keys later on, whereby they will be used to point to array values, you should not change them now.

Then I don't think you want it to look like that.... You want it to look like this:
array(
"canv" => array(
4 => "value",
6 => "value",
9 => "value",
7 => "value"
)
)
You did not specify what values you want, but it may not matter. You can arrive at at that however you want, but if you wind up with an array with (4,6,9,7) in it, you can just do array_flip and it will exchange the keys with the values.

Related

Foreach array return last value

I'm learning OOP and I whould create a list of objects in an array, but my code return the last array
I have search here, but haven't found a solution or idea how to do this.
Excepct
"MerchantDefinedFields":[
{
"Id":2,
"Value":"email#test.com"
},
{
"Id":4,
"Value":"Web"
},
{
"Id":9,
"Value":"NAO"
},
{
"Id":83,
"Value":"Field"
},
{
"Id":84,
"Value":"Only"
}
]
My code
$MDDs = array(
array("Id" => 2, "Value" => "email#test.com"),
array("Id" => 4, "Value" => "Web"),
array("Id" => 9, "Value" => "NO"),
array("Id" => 83, "Value" => "Field"),
array("Id" => 84, "Value" => "Only")
);
foreach($MDDs as $MDD){
$abac = array("Id" => $MDD['Id'], "Value" => $MDD['Value']);
}
Result
Array
(
[Id] => 84
[Value] => PROPRIO
)
Your foreach() is re-setting $abac every time it goes through the loop. So on the last time it runs, it will set the variable to the last item in your array.
Instead of setting the variable each time, try adding the key->value to an array (or something like that, depending on what you want):
$abac = [];
foreach($MDDs as $MDD){
$abac[] = array("Id" => $MDD['Id'], "Value" => $MDD['Value']);
}
It's hard to create the exact right answer for you, since it's unclear what you're trying to accomplish, but this should at least point you in the right direction.
For simple answer :- You don't need foreach loop to get the desired result
you can simply use built-in php function to convert your array to JSON
$abac = json_encode ( $MDDs);
Now coming to your problem :-
you are re-assigning the $abac variable in loop instead of adding values to it like .
$abac = [];
foreach($MDDs as $MDD){
$abac[] = array("Id" => $MDD['Id'], "Value" => $MDD['Value']);
}
The best way to do it is to declare the $abac outside of the foreach and then use the array_push method like this:
$abac = array();
foreach($MDDs as $MDD)
{
array_push($abac, array("Id" => $MDD['Id'], "Value" => $MDD['Value']));
}
print_r($abac);

Pushing array into multidimensional array (php) [duplicate]

This question already has an answer here:
array_push won't give an array, prints out integer value
(1 answer)
Closed 4 years ago.
I've attempted many different ways to push an array into a multidimensional array, including array_push(), $array['index'] = $toPush but I keep being met with quite unexpected results. I have used both var_dump() and print_r() as detailed below in an attempt to debug, but cannot work out the issue.
My reasoning behind is to run a while loop to pull game id's and game names and store these in an assoc. array, and then push them into my main array.
$games_array = array
(
"games" => array
(
array("id"=>"1", "game"=>"first game");
array("id"=>"2", "game"=>"second game");
)
);
// a while loop would run here and update $game_to_add;
$game_to_add = array("id"=>"$game['id']", "game"=>"$game['title']");
$games_array = array_push($games_array['games'], $game_to_add);
In this example, the while() would update the ID and the Game inside of $game_to_add
But, whenever I attempt this it simply overwrites the array and outputs an integer ( example: int(3) )
I don't understand what the problem is, any explination would be appreciated as I cannot find a question specifically for this.
My actual test code:
$games_array = array( "games" => array(
array("id" => "1", "name" => "Star feathers"),
array("id" => "2", "name" => "chung fu")
)
);
$another_game = array("id" => "3", "name" => "some kunt");
$games_array = array_push($games_array["games"], array("id" => "3", "name"
=>"some game"));
var_dump($games_array);
You're assigning the return value of array_push to the games array.
The return value of array_push is the amount of elements after pushing.
Just use it as
array_push($array, $newElement);
(Without assignment)
If you're only pushing one element at he time, $array[] = $newElement is preferred to prevent overhead of the function call of array_push

Array sorting of key values [duplicate]

This question already has answers here:
Preserve key order (stable sort) when sorting with PHP's uasort
(6 answers)
Closed 10 years ago.
I have a poll on my website. For it I put the results into an array such as this:
[Answer1] => "0",
[Answer2] => "1",
[Answer3] => "0",
[Answer4] => "0"
The choice is the key and the number of votes is the value. Essentially when the results show I want to order by the number of votes and then also keep the same sort. So if no votes it would show in the order:
Answer1
Answer2
Answer3
Answer4
But, with "Answer2" having 1 vote it would show:
Answer2
Answer1
Answer3
Answer4
I have tried creating a custom usort function but am having no luck.
Can anybody help me with the logic how to do it please (i can do the PHP myself)?
As you are using an associative array what you are looking for is called a stable sort.
PHP's standard array sorting functions use an unstable implementation of quicksort so as you have found they will not help you here.
You could accomplish this though using array_multisort. By sorting by BOTH the value and the key.
With your data structure you currently have you could not do this with any of the u*sort functions BUT if you modified the data structure and added another dimension so that it looked like the following then you could:
array(
array(
'answer' => 1,
'votes' => 0,
),
array(
'answer' => 2,
'votes' => 1,
),
)
So essentially the comparison function would just need to take into account both sub-indexes.
hope that helps
You want the php function "asort":
http://uk.php.net/manual/en/function.asort.php
it sorts the array, maintaining the index associations.
I've just noticed you're using a standard array (non-associative). if you're not fussed about preserving index associations, use sort( ):
http://uk.php.net/manual/en/function.sort.php
I think asort() will work..
asort($your_array);
Looks like I misread the question.
asort() will sort the array by value, so the highest votes will be first in the array.
thus the result will be:
[Answer2] => "1",
[Answer1] => "0",
[Answer3] => "0",
[Answer4] => "0"
or an even more complete example
[Answer2] => "42",
[Answer3] => "29",
[Answer1] => "18",
[Answer4] => "9"

Get index of an array

I'm having some problems retrieving data from a multidimensional array. I have something like this:
$Act[0] = array(
"Number" => 23,
"Local" => "woods",
"props" => "swords..."
.....
$Act[1] = array(
"Number" => 27,
"Local" => "castle",
"props" => "swords..."
.....
......
$Story[$day] = array(
"Date" => $SDate,
"Acts" => $Acts
);
What I want to do is to get all the numbers from the Act array and use implode to store it in a mysql db.
I tried array_keys but it doesnt work with multi-dimensional arrays. I dont know if it would be even appropriate for this. So basically I want an array with all the values of "Number" of $Story[1]["Acts"], so it would have to go through:
$Story[1]["Act"][0]["Number"]
$Story[1]["Act"][1]["Number"]
$Story[1]["Act"][2]["Number"]
...
So...
$numbers = array_map(function($act) {
return $act["Number"];
}, $Story[1]["Acts"]);
# 23, 27, ...
Is that what you're asking?

Pass array to javascript as array not JSON from PHP

First this is not a duplicate questions. I've looked through some similar problem and most of the answer is what I am using right now.
Here is the problem set up,
on PHP side
$array = array('name' => 'a', 'data' => array('0'=>15,'0.25'=>'18','0.35'=>19,'1' =>20));
echo json_encode($array);
on the JS side
data = $.parseJSON(data); // data is the return from the php script
above
As you can see the $array['data'] is an associative array with numeric number as its key and sorted in order. While parsing into JSON, javascript altered the order of that array and sorted 0 and 1 as numeric key and put them to the head of the object.
I know this is standard behavior for certain browser such as chrome, and IE9.
I've read somewhere that people suggest stick with array strictly if I want to maintain the order of the array.
But my question is how do you feed back an array from PHP to javascript as an array instead of using json object? Or is there other solution to this kind of problem . Thanks for the input in advance.
Thanks for the input in advance
Use an array to maintain order, and then an object to create the map. There are two ways. I would suggest:
$array = array('name' => 'a', 'data' =>
array(
array('key' => 0, 'value' => 15),
array('key' => 0.25, 'value' => 18),
array('key' => 0.35, 'value' => 19),
array('key' => 1, 'value' => 20),
)
);
echo json_encode($array);
Which will give you the JSON:
{
"name": "a",
"data": [
{"key": 0, "value": 15},
{"key": 0.25, "value": 18},
{"key": 0.35, "value": 19},
{"key": 1, "value": 20}
]
}
Then you will have order but to look up a certain key will be more difficult. If you want that to be easy you can return a mapping object as well like this:
$array = array('name' => 'a', 'data' =>
array(
"0" => 15,
"0.25" => 18,
"0.35" => 19,
"1" => 20,
),
'order' => array("0", "0.25", "0.35", "1")
);
echo json_encode($array);
Which will give you:
{
"name": "a",
"data": {
"0": 15,
"0.25": 18,
"0.35": 19,
"1": 20
},
"order": ["0", "0.25", "0.35", "1"]
}
One of these two methods of returning your data should prove to be the most useful for your specific use case.
Actually, it's PHP that takes the "0" and "1" keys and makes them numeric keys. This has nothing to do with your JavaScript.
There isn't any real way to work around this, but ideally your code should not rely on such things as "what order the keys of an object are in". It may be a better idea, just from what I see here, to separate the data into an array of keys and an array of values, then zip them back together on the JS side.
I'd suggest another field for storing order.
$array = array('name' => 'a',
'data' => array('0'=>15,'0.25'=>'18','0.35'=>19,'1' =>20),
'order'=> '0,0.25,0.35,1'
);
echo json_encode($array);

Categories