I am working with a multidimensional array that I want to conditionally add keys to and am not getting the output I desire. At the core of the issue is the following code:
$data[$CSVKey] = array (
'key1' => $key1value,
);
$data[$CSVKey] = array (
'key2' => $key2value,
);
What I would expect to happen when I work with the array at a later time is that there would be a multidimensional array with both key 1 and key 2, but I am not getting that. when I work with it, I only see 'key2'. However when I change it to this:
$data[$CSVKey] = array (
'key1' => $key1value,
'key2' => $key2value,
);
I see the array as I desire. Can I not populate a multidimensional array this way?
You are replacing whatever value $data[$CSVKey] is each time you assign a new array.
You should just continue using your bracket notation to assign your values:
$data[$CSVKey]['key1'] = $key1value;
$data[$CSVKey]['key2'] = $key2value;
Or you could use array_merge() if you wanted to add more than one element to the array in one call:
$data[$CSVKey] = array_merge($data[$CSVKey], ['key1' => $key1value, 'key2' => $key2value])
Related
So, I was designing a function that can take multiple arguments via the spread operator (...$arg)
but it can also take a simple input array.
I want to access the first element of the array with the array_slice() method, but it doesn't work as expected:
// This is what the spread argument passes into the function if it gets a single array
$arg = [
['value1', 'value2', 'valueN'],
];
// Accessing first element via array_slice:
var_export( array_slice($arg, 0, 1) );
Expected result:
array (
0 => 'value1',
1 => 'value2',
2 => 'valueN',
)
The result is basically equal to the input array:
array (
0 =>
array (
0 => 'value1',
1 => 'value2',
2 => 'valueN',
),
)
I know I can just simply access the 0th element ($arg[0]) to get the first item, but I'm curious why array_slice() doesn't work as I would expect. What am I missing here?
You are expecting the first value from your array. array_slice return the sliced array. You can use array_shift instead which will shifts the first value of the array off and returns it.
print_r(array_shift($arg));
Output:
array (
0 => 'value1',
1 => 'value2',
2 => 'valueN',
)
It's working as expected. It's returning the first element of your $arg array, which is the array with the key 0 containing an array by itself and not the contents of the first element. You're just misunderstanding how array_slice actually works.
array (
0 =>
array (
0 => 'value1',
1 => 'value2',
2 => 'valueN',
),
)
I am trying to figure out how to reorganize an array..
I have a multidimensional array(Ill call that original_array) and I would like to take the first array within original_array and set the values as keys in a new array. I also want to take the values of the second array in original_array and make them keys and then set the values of the third array in original_array as the values for those keys.
Here is an example of original_array:
Array (
[id] => Array (
[0] => 1
[1] => 3
)
[reward] => Array (
[0] => Movie
[1] => Trip
)
[cost] => Array (
[0] => 50
[1] => 200
)
)
Basically what I would like to do is look like this:
Array (
[1] => Array (
[Movie] => 50
)
[3] => Array (
[Trip] => 200
)
)
Is there a simple and elegant way to merge these like this?
I have spent hours trying to figure this out using array_merge, array_merge_recursive.. etc. And have search SO far and wide for a similar questions, but I haven't found anything that does what I am after.
I was able to correctly combine the 2nd and 3rd arrays in original_array with array_combine. But, I am at a loss as how to combine that result with the 1st array's values in original_array.
Thanks in advance to any help!
Well, the dirty way would be just use combine array functions like array_combine with the input:
$new_array = array_combine(
$array['id'], // parent keys
// combine chunked combined sub keys :p
array_chunk(array_combine($array['reward'], $array['cost']), 1, true)
);
There may be some incantation of array_*() merging functions that could produce what you're looking for, but it is far easier to just iterate over the original array's [id] sub-array and use its values to create new sub-array keys in a different output array.
// To hold your output
$output = array();
// Iterate the original array's [id] sub-array
foreach ($original['id'] as $idxkey => $newkey) {
// Add a sub-array using $newkey to the output array
$output[$newkey] = array(
// Using the index (not value), retrieve the corresponding reward
// value to use as the new array key
// and corresponding cost to use as the new subarray value
$original['reward'][$idxkey] => $original['cost'][$idxkey]
);
}
Here is a demonstration: https://3v4l.org/2pac3
This should work for you:
First you can get the keys for the main array into a separate variable with array_shift(), which will just remove the first element from your array, which is the array holding the keys.
Then use array_map() to loop through both of your subArrays and use reward as key with the cost values as value and return it in an array. At the end you just have to array_combine() your keys $keys with the new created array.
Code:
<?php
$keys = array_shift($arr);
$result = array_combine($keys, array_map(function($k, $v){
return [$k => $v];
}, $arr["reward"], $arr["cost"]));
print_r($result);
?>
You might wanna take a look at BaseArrayHelper from Yii 2.0 Framework.
Although this file is part of a framework it has only very few dependencies and you should be able to use just this file or parts of it in your code with small modifications.
An example for your use case can be found in the index() method.
I have a function that returns an array where the value is an array like below: I want to ignore the key and extract the value directly. How can I do this without a for loop? The returned function only has one key but the key (2 in this case) can be a variable
Array ( [2] => Array ( [productID] => 1 [offerid]=>1)
Expected result:
Array ( [productID] => 1 [offerid]=>1)
There're at least 3 ways of doing this:
Use current function, but be sure that array pointer is in the beginning of your array:
$array = Array (2 => Array ( 'productID' => 1, 'offerid' => 1));
$cur = current($array);
var_dump($cur, $cur['offerid']);
Next is array_values function, which will give you array of values with numeric keys, starting with 0
$array = Array ( 2 => Array ( 'productID' => 1, 'offerid' => 1));
$av = array_values($array);
var_dump($av[0], $av[0]['offerid']);
And third option is use array_shift, this function will return first element of array, but be careful as it reduces the original array:
$array = Array ( 2 => Array ( 'productID' => 1, 'offerid' => 1));
$first = array_shift($array);
var_dump($first, $first['offerid']);
If you want to get the current value of an array, you can use current() assuming the array pointer is in the correct position. If there is only one value, then this should work fine.
http://php.net/manual/en/function.current.php
I think Devon's answer will work for you , but if not your can try
$arr = array_column($arr, $arr[2]);
if you need always the second index of your master array, if you need all index use
array_map(),
something like array_map('array_map', $arr); should work.
I want to set the value of an associative array using the array index of the key/value pair. For example:
$my_arr = array( "bling" => "some bling", "bling2" => "lots O bling" );
$my_arr[1] = "not so much bling"; // Would change the value with key bling2.
How can this be accomplish this without using the key string?
Use array_keys.
$keys = array_keys($my_arr);
$my_arr[$keys[1]] = "not so much bling";
There is no correlation between numeric and associative index keys.
When you say you want to set the value of an associative array using the array index of the key/value, then you have to use the given key, setting $array[1] is not the same as setting $array['foo'].
Consider this array
print_r( array('foo', 'foo' => 'bar', 'baz', 'some' => 'value') );
This will give
Array
(
[0] => foo
[foo] => bar
[1] => baz
[some] => value
)
The foo is the second element in the array. That's the offset, but it has nothing to do with the index 1. As you can see, in that array above, index 1 is associated with baz. It is wrong to assume that just because foo is the first associative key it has anything to do with the actual numeric key 1. Just like some does not correlate to 2.
Likewise, for a mixed array like shown above, the solution with array_keys suggested elsewhere on this site will not work, because
print_r( array_keys(array('foo', 'foo' => 'bar', 'baz', 'some' => 'value')) );
will give
Array
(
[0] => 0
[1] => foo
[2] => 1
[3] => some
)
So when you do $array[$keys[1]] you are really doing $array['foo']. But if you wanted to access the second associative value in that array ('some'), you cannot do $array[$keys[2]] because that would evaluate to $array[1] and that's baz.
The Offset of an element is completely unrelated to it's key or value
print_r(
array(
100 => 'foo',
'foo' => 'bar',
50 => 'baz',
'some' => 'value'
)
);
really means
Array
( //key value offset/position
[100] => foo // 0
[foo] => bar // 1
[50] => baz // 2
[some] => value // 3
)
which means the element at offset 0 is foo although it's key is 100. If you want to extract elements from an array by offset, you have to use
$third = array_splice($array, 2, 1);
echo $third[0]; // baz
This would create an array holding only the element at the third position.
Or you could use an ArrayIterator. The ArrayIterator implements a Seekable interface that lets you seek to a specific position/offset in the array and then fetch that:
$iterator = new ArrayIterator($array);
$iterator->seek(3);
echo $iterator->current(); // value
Whilst array_keys() allows access to the nth key, array_values will give you the nth value.
<?php
$array = [
0 => 'Zero',
'1' => 'One',
'Two' => 'Two',
];
echo array_values($array)[2];
?>
will output 'Two'.
Is there an advantage of one over the other? Well, the only minor one I can see is the number of array accesses.
With array_keys() you need to 3.
Get the keys from the data array.
Get the nth key from the list of keys.
Get the value using the nth key from the data array.
With array_values(), you only need 2.
Get the values from the data array.
Get the nth value from the list of values.
But, on the other hand, keys are normally smaller and the data could be hugely nested, so, on balance, using the array_keys() is probably safer.
If the array is large, both array_keys and array_values will be wasteful since they will allocate a new array the same size as the original, just to get the nth key (or value).
array_slice accepts an integer offset and works on associative arrays. You can use it to get (and set) the nth key in constant time.
// This will at most allocate 2 temporary arrays of 1 element each
$key = array_keys(array_slice($array, $n, 1, true))[0];
$array[$key] = $value;
Try this. It works for you.
$result= array_values($my_arr); // Array with indexes you need
Another possibility is to convert it to a normal array:
$arraybuff = implode("~~~",$my_arr);
$my_arr = explode("~~~",$arraybuff);
Where "~~~" is a delimiter that wont occur in your data.
Now you can access the array using numerical indexes equal to the offsets.
If you still need to retain your associative array, just assign it to a different variable.
Good day everyone.
I have an regular array (this is the print_r result, the array can have from 1 to n positions):
Array
(
[1] => value1
[2] => value2
[3] => value3
)
I have another array defined elsewhere as:
$array_def['value1']['value2']['value3'] = array(
'fl' => 'field1',
'f2' => 'field2',
);
Using the first array result, how can i check if $array_def exists? In other words, i need to use a flat array values to check if a multidimensional array correspondence exists; keep in mind that the values can repeat in the first array, therefore flipping values with keys it's not an option as it will collide and remove duplicated values.
Thanks in advance.
You can do it this way:
$a = array(1=>'value1', 2=>'value2', 3=>'value3');
$array_def[$a[1]][$a[2]][$a[3]] = array(
'fl' => 'field1',
'f2' => 'field2',
);
I don't think there's any shortcut or special built-in function to do this.
Found the perfect function for you. returns not only exists, but position within a multi-dimensional array..
http://www.php.net/manual/en/function.array-search.php#47116
dated: 03-Nov-2004 11:13
too much to copy/paste
you can then loop over your flat array and foreach:
multi_array_search($search_value, $the_array)