Array_slice() doesn't work as expected on nested arrays - php

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',
),
)

Related

Is there way to change values of array given from another array

$original array [['type_of_activity'=>'م.ص','total'=>'0' ],['type_of_activity'=>'م.و','total'=>'0'],['type_of_activity'=>'م.ن','total'=>'0'],['type_of_activity'=>'م.خ','total'=>'0'],['type_of_activity'=>'م.ت','total'=>'0'],['type_of_activity'=>'و.ش','total'=>'0'],['type_of_activity'=>'ق.ع','total'=>'0'],
['type_of_activity'=>'م.و','total'=>'0'],['type_of_activity'=>'م.غ','total'=>'0'],['type_of_activity'=>'س.ن','total'=>'0'],['type_of_activity'=>'ح.ف','total'=>'0']]
that there areport based on this value
the return array from DB my be ['type_of_activity'=>'م.و','total'=>'5'],['type_of_activity'=>'م.غ','total'=>'10'],['type_of_activity'=>'س.ن','total'=>'15']
is there a way to map this array to the original array where the match keys
without losing any key or value
the result will be just 11 arrays within the original
[['type_of_activity'=>'م.ص','total'=>'0' ],
[['type_of_activity'=>'م.ع','total'=>'0' ],
['type_of_activity'=>'م.و','total'=>'5'],['type_of_activity'=>'م.ن','total'=>'0'],['type_of_activity'=>'م.خ','total'=>'0'],['type_of_activity'=>'م.ت','total'=>'0'],['type_of_activity'=>'و.ش','total'=>'0'],['type_of_activity'=>'ق.ع','total'=>'0'], ['type_of_activity'=>'م.غ','total'=>'10'],['type_of_activity'=>'س.ن','total'=>'15'],['type_of_activity'=>'ح.ف','total'=>'0']],
You can use array_merge,
$c = array_merge($a,$b);
print_r($c);
Demo
O/p
Array
(
[mw] => 0
[mg] => 5
[ma] => 0
[sn] => 0
[fa] => 0
[mn] => 10
)

PHP: Ignore key and extract value of an array

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.

PHP Write to a Multidimensional Array at 2 points in time

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])

Array in array in array

I'm a bit struggling with the associative arrays in associative arrays. Point is that I always have to drill deeper in an array and I just don't get this right.
$array['sections']['items'][] = array (
'ident' => $item->attributes()->ident,
'type' => $questionType,
'title' => $item->attributes()->title,
'objective' => (string) $item->objectives->material->mattext,
'question' => (string) $item->presentation->material->mattext,
'possibilities' => array (
// is this even neccesary to tell an empty array will come here??
//(string) $item->presentation->response_lid->render_choice->flow_label->response_label->attributes()->ident => (string) $item->presentation->response_lid->render_choice->flow_label->response_label->material->mattext
)
);
foreach ($item->presentation->response_lid->render_choice->children() as $flow_label) {
$array['sections']['items']['possibilities'][] = array (
(string) $flow_label->response_label->attributes()->ident => (string) $flow_label->response_label->material->mattext
);
}
So 'possibilities' => array() contains an array and if I put a value in it like the comment illustrates I get what I need. But an array contains multiple values so I am trying to put multiple values on the position $array['sections']['items']['possibilities'][]
But this outputs that the values are stores on a different level.
...
[items] => Array
(
[0] => Array
(
[ident] => SimpleXMLElement Object
(
[0] => QTIEDIT:SCQ:1000015312
)
[type] => SCQ
...
[possibilities] => Array
(
)
)
[possibilities] => Array
(
[0] => Array
(
[1000015317] => 500 bytes
)
[1] => Array
...
What am trying to accomplish is with my foreach code above is the first [possibilities] => Array is containing the information of the second. And of course that the second will disappear.
Your $array['sections']['items'] is an array of items, so you need to specify which item to add the possibilities to:
$array['sections']['items'][$i]['possibilities'][]
Where $i is a counter in your loop.
Right now you are appending the Arrays to [items]. But you want to append them to a child element of [items]:
You do:
$array['sections']['items']['possibilities'][] = ...
But it should be something like:
$array['sections']['items'][0]['possibilities'][] = ...
$array['sections']['items'] is an array of items, and as per the way you populate the possibilities key, each item will have it's own possibilities. So, to access the possibilities of the item that is being looped over, you need to specify which one from $array['sections']['items'] by passing the index as explained in the first answer.
OR
To make things simpler, you can try
Save the item array (RHS of the first =) to a separate variable instead of defining and appending to the main array at the same time.
Set the possibilities of that variable.
Append that variable to the main $array['sections']['items']
I have:
array[{IsChecked: true, SEC: 0, STP: 0},
{IsChecked: ture ,SEC: 0, STP: 1},
{IsChecked: false, SEC: 1 ,STP: 0}]
How to get each SEC where IsCheked value is true?

Fetching a multidimensional array

I am trying to edit a plugin that is fetching a multidimensional array, then breaking it out into a foreach statement and doing stuff with the resulting data.
What I am trying to do is edit the array before it gets to the foreach statement. I want to look and see if there is a key/value combination that exists, and if it does remove that entire subarray, then reform the array and pass it to a new variable.
The current variable
$arrayslides
returns several subarrays that look like something like this (I remove unimportant variables for the sake of briefness):
Array (
[0] => Array (
[slide_active] => 1
)
[1] => Array (
[slide_active] => 0
)
)
What I want to do is look and see if one of these subarrays contains the key slide_active with a value of 0. If it contains a value of zero, I want to dump the whole subarray altogether, then reform the multidimensional array back into the variable
$arrayslides
I have tried a few array functions but have not had any luck. Any suggestions?
$arrayslides = array(0 => array ( 'slide_active' => 1, 'other_data' => "Mark" ),
1 => array ( 'slide_active' => 0, 'other_data' => "ABCDE" ),
2 => array ( 'slide_active' => 1, 'other_data' => "Baker" ),
3 => array ( 'slide_active' => 0, 'other_data' => "FGHIJ" ),
);
$matches = array_filter($arrayslides, function($item) { return $item['slide_active'] == 1; } );
var_dump($matches);
PHP >= 5.3.0
I know its not so efficient but still
foreach ($arraySlides as $key => $value)
{
if(in_array('0', array_values($value))
unset($arraySlides[$key]);
}

Categories