Manually creating an associative array - php

I'm trying to create an associative array with dynamic data, and having some trouble.
I'd like to produce an array that looks like the following while fetching rows from a MySQL query.
Array
(
[0] = Array
(
[name] => First
)
[1] = Array
(
[name] => Second
)
[2] = Array
(
[name] => Third
)
[3] = Array
(
[name] => Fourth
)
[4] = Array
(
[name] => Fifth
)
)
I've been trying to use array_merge, but it's not giving me the result I want. Array_merge apparently doesn't operate the same inside a foreach as it does outside (I ran the same code with and without the loop, without worked the way I need).
Basically, this is what I'm doing currently (which doesn't work):
foreach($idList as $id)
{
$arr[] = array_merge(array(), array('name' => $id));
}
This gives me output like this:
Array
(
[0] = Array
(
[name] => first
)
[1] = Array
(
[0] = Array
(
[name] => first
)
[name] => second
)
[2] = Array
(
[0] = Array
(
[name] => first
)
[1] = Array
(
[0] = Array
(
[name] => first
)
[name] => second
)
[name] => third
)
)

You've got a few issues here.
Mainly, you can't have the same index twice. 'name' can be the index once and only once, so you're 'desired' output is impossible.
Also, this statement is pretty problematic
foreach($idList as $id)
{
$arr[] = array_merge(array(), array('name' => $id));
}
The use of $arr[] = $x is like a push. It adds a new element to the back of the array, numerically indexed.
Your use of array_merge is unnecessary. array_merge returns the second argument merged over the first argument. You are just trying to add a single new element. Also, is that exactly the line you used or did you use array_merge($arr, array('name' => $id)); ???
Try:
foreach($idList as $id)
{
$arr[] = array('name' => $id);
}
And you will get:
Array
(
[0] = Array
(
[name] => first
)
[1] = Array
(
[name] => second
}
....
And so on. I'm not sure if this is exactly what you want, but what you proposed in the first place isn't possible.

Related

Array stacking over another array

I'm trying to add an item to an array, but the arrays keep stacking over one another and it becomes unusable.
I have tried different methods and I can make it work if my input doesn't come from get_user_meta() and instead I create a custom string to test the array. But I need to load the meta so I can just add additional content into it.
$user_id = get_current_user_id();
$the_id = get_the_ID();
$continue_watching = get_user_meta($user_id,'continue_watching',false);
if ( !isset($continue_watching) ) {
$continue_watching = array();
}
$continue_watching[] = $the_id;
update_user_meta($user_id,'continue_watching',$continue_watching);
This is what is happening:
Array (
[0] => Array
(
[0] => Array
(
[0] => 16966
[1] => 16966
)
[1] => 11234
)
[1] => 16951
)
But I expected the output to look like this:
Array (
[0] => 11234
[1] => 16951
[2] => 16966
[3] => 16970
)
Update:
I have reset the array and this is the output just after $continue_watching = get_user_meta($user_id,'continue_watching',false);
Array
(
)
This is the output after $continue_watching[] = $the_id;
Array
(
[0] => 16955
)
After opening another page, this is the output after $continue_watching = get_user_meta($user_id,'continue_watching',false);
Array
(
[0] => Array
(
[0] => 16955
)
)
And this is the output after $continue_watching[] = $the_id;
Array
(
[0] => Array
(
[0] => 16955
)
[1] => 16957
)
After trying all the alternatives, it turned out to be a very simple solution. All I had to do was change the value from false to true inside the wordpress function get_user_meta($user_id,'continue_watching',false);
The "false" option was displaying the array inside another array, when I changed it to "true" the output was the array contained inside the variable alone.

JS array to combine into one array

I have following js array using serialisedArray -
Array
(
[0] => Array
(
[name] => sub_maintenance_template[1][maintenance_location_id]
[value] => 54321
)
[1] => Array
(
[name] => sub_maintenance_template[1][maintenance_problem_id]
[value] => 65432
)
[2] => Array
(
[name] => sub_maintenance_template[1][maintenance_priority_id]
[value] => 76896
)
[3] => Array
(
[name] => sub_maintenance_template[1][description]
[value] => sample description
)
)
Expected array -
[sub_maintenance_template] => Array (
[1] =>
(
[maintenance_location_id]=> 54321
[maintenance_problem_id]=> 65432
[maintenance_priority_id]=>76896
[description]=> sample description
)
)
I tried like this-
foreach( $tableData as $key => $value ) {
echo $key;
$newArray['sub_maintenance_template'][3][] = $value['name'];
$newArray['sub_maintenance_template'][3][] = $value['value'];
}
Even though I iterate it through foreach but failed to get desired output. IS there any way to get desired one?
It would be better to pass these as actual arrays in GET or POST, but since the string in name is how arrays would be passed in a URL query string, you can use parse_str:
foreach($array as $values) {
parse_str("{$values['name']} = {$values['value']}", $result);
}
print_r($result);
Or another way; extract and build key/value pairs to build a query string and then parse it:
parse_str(http_build_query(array_column($array, 'value', 'name')), $result);
print_r($result);

Using array_flip() to return an array

I have an array:
$input = array(1,2,3,4,6,5,3,6)
and I want the key/value pairs to be flipped.
This can be done by using the array_flip() function.
$flipped = array_flip($input)
If in the original array has 2 or more same values (in this case number 6)how can I return it in an array?
array= ([1]=0,[2]=>1,[4]=>2,[6]=>array(3,6),[5]=>4,[3]=>5)
I tried to use array_count_values() but can't figure out how to do it?
You cannot do that using the array_flip() function. Probably you look for something like that:
<?php
function array_flip_and_collect($input) {
$output = [];
foreach ($input as $key=>$val) {
$output[$val][] = $key;
}
return $output;
}
$input = array(1,2,3,4,6,5,3,6);
print_r(array_flip_and_collect($input));
The output:
Array
(
[1] => Array
(
[0] => 0
)
[2] => Array
(
[0] => 1
)
[3] => Array
(
[0] => 2
[1] => 6
)
[4] => Array
(
[0] => 3
)
[6] => Array
(
[0] => 4
[1] => 7
)
[5] => Array
(
[0] => 5
)
)
Note that the output differs slightly from what you suggested in your question. That is by purpose because this appears more logical to me. If you really want that keys with only one element really are scalars and not arrays with one element, then you have to add an additional conversion step to the code.

Remove array from a multidimensional array if the same value exists in another multidimensional array

I have two arrays like
Array
(
[0] => Array
(
[id] => 1
[controller] => users
[action] => index
)
[1] => Array
(
[id] => 1
[controller] => users
[action] =>
)
[2] => Array
(
[id] => 1
[controller] => users
[action] => login
)
)
Array
(
[0] => Array
(
[id] => 1
[controller] => users
[action] => index
)
[1] => Array
(
[id] => 1
[controller] => users
[action] =>
)
[2] => Array
(
[id] => 1
[controller] => users
[action] => logout
)
)
I want to remove complete nested array from 1st array if a match is found in 2nd array (Based on keys ['controller'] &&['action']). So in the first array only the 3rd [2] array is unique.
The output should be like :
Array
(
[0] => Array
(
[id] => 1
[controller] => users
[action] => login
)
)
Please Note
Please note that the 2nd array doesn't necessary to be in same order as first. As opposed in my question where the first two arrays of each array are identical.
What i have tried is :
$result = array();
for($i=0; $i < count($a); $i++)
{
$result[] = array_diff($a[$i], $b[$i]);
}
print_r($result); // This doesn't give required output. It removes every thing and return like
Array
(
[0] => Array
(
)
[1] => Array
(
)
[2] => Array
(
[action] => login
)
)
Have a look at this answer. I think it'll do exactly what you need it to.
There are numerous ways you could go about this. Here's one that I think would be pretty simple.
First up, setup a new array based on $a, indexing it by the controller and action attributes.
$final = array();
foreach($a AS $item) {
$final[$item['controller'] . $item['action']] = $item;
}
Now you can loop through the second array, removing any matching items.
foreach($b AS $item) {
unset($final[$item['controller'] . $item['action']]);
}
Now $final should be the array you want.
Working example: http://3v4l.org/JtUkN
Here is my own working solution
for($i=0; $i < count($data); $i++)
{
foreach($this->existing_data as $v)
{
if( ($v['controller'] == $data[$i]['controller']) && ($v['action'] == $data[$i]['action']) )
{
unset($data[$i]);
break;
}
}
}

php - merge arrays keeping keys and incrementing

I've been trying to figure this one out all day but cant seem to explain, or get across what I'm trying to achieve. Lets say I have 2 arrays:
Array
(
[1] => Array
(
[2] => Dashboard
)
)
and
Array
(
[1] => Array
(
[3] => Toasts
)
)
What I want to be able to do is merge the 2 arrays as follows:
Array
(
[1] => Array
(
[2] => Dashboard,
[3] => Toasts
)
)
But, if I have something like this:
Array
(
[1] => Array
(
[2] => Dashboard
)
)
Array
(
[1] => Array
(
[2] => Toasts
)
)
I dont want to loose the value of the overriding element but increment it like so
Array
(
[1] => Array
(
[2] => Dashboard,
[3] => Toasts
)
)
I have tried everything from array merge, recursive merge and even eval but I just can get my head around it. Has anyone come across this before? a function I haven't found?
You should be using $array['indexname'] = 'value';. array_merge() or array_push() doesn't maintain the values having same/associative keys while merging, because there is no way to determine the next key.
Maybe not a real answer but just a way to escape overwriting;
$a1 = array(array(2 => 'Dashboard'));
$a2 = array(array(3 => 'Toasts'));
$a3 = array(array(3 => 'Foo'));
$array = array();
foreach (array_merge($a1, $a2, $a3) as $a) {
foreach ($a as $i => $value) {
if (!isset($array[$i])) {
$array[$i] = $value;
} else {
$array[] = $value;
}
}
}
print_r($array);
Array
(
[2] => Dashboard
[3] => Toasts
[4] => Foo
)

Categories