Reputation: 91
I have an array:
Array
(
[0] => Item
[1] => Repaired Wattles
[2] => Types
[3] => Non-Wire
[4] => Estimated Qty
[5] => 124
[6] => Actual Qty
[7] => 124
[8] => Upload File
[9] => example.jpg
)
I need to add the next value to the previous. I need it to look like this
Array
(
[Item] => Repaired Wattles
[Types] => Non-Wire
[Estimated Qty] => 124
[Actual Qty] => 124
[Upload File] => example.jpg
)
I have something along the lines of this:
$array = array(
foreach($stri as $string) {
$stri[] => $stri[$val]
$val = $string + 1;
);
I know I am definitely wrong. But right here I'm stuck and don't know how to get my code working as I want it to.
Upvotes: 0
Views: 143
Reputation: 129
$a = array(0 => 'Item',
1 => 'Repaired',
2 => 'Types',
3 => 'Non',
4=> 'Estimated',
5 => '124',
6 => 'Actual',
7 => '124',
8 => 'Upload',
9 => 'example'
);
echo "<pre>";
print_r($a);
$a_len = count($a);
$fnl = array();
$i = 0;
while($i<$a_len){
$fnl[$a[$i]] = $a[++$i];
$i++;
}
print_r($fnl);
Upvotes: 0
Reputation: 3337
Write simple for
loop and increment counter by 2 in each loop:
$result = array();
for ($i = 0; $i < count($arr); $i += 2) { // increment counter +2
if (isset($arr[$i]) && isset($arr[$i+1])) { // to make sure if both indexes exists in array
$result[$arr[$i]] = $arr[$i+1];
}
}
Usage examples:
$arr = array('aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff');
// ...
var_dump($result);
array(3) {
'aaa' =>
string(3) "bbb"
'ccc' =>
string(3) "ddd"
'eee' =>
string(3) "fff"
}
$arr = array('aaa', 'bbb', 'ccc', 'ddd', 'eee');
// ...
var_dump($result);
array(2) {
'aaa' =>
string(3) "bbb"
'ccc' =>
string(3) "ddd"
}
Upvotes: 2
Reputation: 969
use the following code
echo "<pre>";
$myArr = array('Item', 'Repaired Wattles','Types', 'Non-Wire', 'Estimated Qty', '124', 'Actual Qty', '124', 'Upload File', 'example.jpg');
print_r($myArr);
$total = count($myArr);
$newArr = array();
for($i=0; $i<$total;$i++) {
$newArr[$myArr[$i]] = $myArr[$i+1];
$i++;
}
print_r($newArr);
Upvotes: 1
Reputation: 21437
You can try array_combine
along with array_column
and array_chunk
.
Note: This'll work if the array is perfectly have even number of values
$arr = Array('Item','Repaired Wattles','Types','Non-Wire','Estimated Qty',124,'Actual Qty',124,'Upload File','example.jpg');
$final = array_combine(array_column(array_chunk($arr, 2),0),array_column(array_chunk($arr, 2),1));
print_r($final);
Upvotes: 1
Reputation: 59691
This should work for you:
First array_chunk()
your array into chunks of 2. After this just use array_column()
to get the 0 column as key and column 1 as value. Like this:
$arr = array_column(array_chunk($arr, 2), 1, 0);
Upvotes: 1