How can I achieve this in Array in PHP

59
June 15, 2018, at 11:50 AM

am having problem achieving this result with array, I want to update another empty array with data in first array in such a way that the first two rows is ommitted and the first 3rows is added to the index 0 of the empty array, and the next 3 rows is also updated to the second index and so on. I have this Array in

`$arr = [
    'tqty' => 9,
    'tPrice' => 18700,
    'food_name_1' => 'Black Coffee',
    'food_quanty_1' => 1,
    'food_price_1' => 1000,
    'food_name_2' => 'Sub Combo',
    'food_quanty_2' => 2,
    'food_price_2' => 3000
];`

I want to use this array data and update another empty array this way, removing the first two rows

$arr2 = [
    0 => [
         'food_name_1' => 'Black Coffee',
         'food_quanty_1' => 1,
        'food_price_1' => 1000
    ],
   1 => [
         'food_name_2' => 'Sub Combo',
         'food_quanty_2' => 2,
        'food_price_2' => 3000
    ]
];

here is my code so far

$arr = [
    'tqty' => 9,
    'tPrice' => 18700,
    'food_name_1' => 'Black Coffee',
    'food_quanty_1' => 1,
    'food_price_1' => 1000,
    'food_name_2' => 'Sub Combo',
    'food_quanty_2' => 2,
    'food_price_2' => 3000
];
$newdat = [];
$count = 0;
$oldcount = 1;
foreach($arr as $key => $value){
    if(preg_match_all('!\d+!', $key, $matches)){
        if($oldcount == $matches[0][0]){
            $newdat[$matches[0][0]] = [
                $count => [
                    $key => $value
                ]
                ];
        } else{
            $count = 0;
            $oldcount = $matches[0][0];
        }
    }
    $count++;
 }

I hope I get help soon. thanks

Answer 1

If I have understood you correctly,

$newdata = array();
for ($i = 1; $i++;) { // Intentionally no condition set.
    if (array_key_exists('food_name_' . $i, $arr)) {
        $temparray = array();
        $temparray['food_name_' . $i] = $arr['food_name_' . $i];
        if (array_key_exists('food_quanty_' . $i, $arr)) {
            $temparray['food_quanty_' . $i] = $arr['food_quanty_' . $i];
        }
        if (array_key_exists('food_price_' . $i, $arr)) {
            $temparray['food_price_' . $i] = $arr['food_price_' . $i];
        }
        $newdata[] = $temparray;
    } else {
        break; // break out of the loop
    }
}
echo "<pre>";
print_r($newdata);
echo "</pre>";
die();
Answer 2

Assuming the array keys and order stay consistent you could use array_chunk

<?php 
$inArray = [
    'tqty' => 9,
    'tPrice' => 18700,
    'food_name_1' => 'Black Coffee',
    'food_quanty_1' => 1,
    'food_price_1' => 1000,
    'food_name_2' => 'Sub Combo',
    'food_quanty_2' => 2,
    'food_price_2' => 3000,
];
$outArray = [];
// Remove first 2 values.
$inArray = array_slice( $inArray, 2 );
// 'Chunk' the rest of the values.
// true preserves keys.
$outArray = array_chunk( $inArray, 3, true );
echo '<pre>' . print_r( $outArray, true ) . '</pre>';
/**
    Output:
    <pre>Array
    (
        [0] => Array
            (
                [food_name_1] => Black Coffee
                [food_quanty_1] => 1
                [food_price_1] => 1000
            )
        [1] => Array
            (
                [food_name_2] => Sub Combo
                [food_quanty_2] => 2
                [food_price_2] => 3000
            )
    )
    </pre>
 */
Answer 3

Loop through it and build the array index string via variables.

<?php
$arr = [
    'tqty' => 9,
    'tPrice' => 18700,
    'food_name_1' => 'Black Coffee',
    'food_quanty_1' => 1,
    'food_price_1' => 1000,
    'food_name_2' => 'Sub Combo',
    'food_quanty_2' => 2,
    'food_price_2' => 3000
];
foreach(array("food_name_","food_quanty_","food_price_") as $v){

// replace the set value of 2 here with a count() on the $arr
// and some basic math - IF you are always sure you'll have 3 fields
    for($i=0;$i<2;$i++){
        $newarr[$i][$v.($i+1)]=$arr[$v.($i+1)];
    }
}
print_r($newarr);

 ?>
Answer 4

Here's a solution that will locate the _x at the end to check its a digit

This solution does not worry about how many non numbered fields you have, or how many fields there are per numbered "row", they are also indexed based on the _x number.

$arr = [
  'tqty' => 9,
  'tPrice' => 18700,
  'food_name_1' => 'Black Coffee',
  'food_quanty_1' => 1,
  'food_price_1' => 1000,
  'food_name_2' => 'Sub Combo',
  'food_quanty_2' => 2,
  'food_price_2' => 3000
];
$arr2 = array();
foreach( $arr as $key => $value )
{
  $explode = explode( '_', $key );
  if( ctype_digit( $index = end( $explode ) ) === true)
  {
    if( isset( $arr2[ $index ] ) === false )
    {
      $arr2[ $index ] = array();
    }
    $arr2[ $index ][ substr( $key, 0, strlen( $key ) - 1 - strlen( $index ) ) ] = $value;
  }
}
print_r( $arr2 );

Output:

Array
(
    [1] => Array
        (
            [food_name] => Black Coffee
            [food_quanty] => 1
            [food_price] => 1000
        )
    [2] => Array
        (
            [food_name] => Sub Combo
            [food_quanty] => 2
            [food_price] => 3000
        )
)
Answer 5

If you already know that you need always the same indexes from $arr, you can use the array_keys function in order to index the associative array.
Example:

$keys = array_keys($arr);
echo '<br><br>'.$arr[$keys[1]];


Here is a complete example:

$keys = array_keys($arr);    #stores the associative keys by index
$arr2 = array();
/* For each array $arr do the following */
$limit = 5; #substitute this with: count($arraylist)
for( $n_array=0; $n_array<limit; $n_array++ ){
    $cur_arr = array(); #substitute with your: $arraylist[ $n_array ]
    for( $a = 2; $a<count($arr); $a++ ){
        $cur_arr[ $keys[$a] ] = $arr[ $keys[$a] ];
    }  
    $arr2[ $n_array ] = $cur_arr;
}

Hope it will be helpful

READ ALSO
MySQL Query Optimization to get montly report

MySQL Query Optimization to get montly report

I need to optimize a queryScript return a simple table result like this below

66
htaccess rewrite a multi-query string into a path

htaccess rewrite a multi-query string into a path

How would i go about changing the query string

59
One mysqli connection for multiple database functions

One mysqli connection for multiple database functions

My main page calls many database functions, stored in the dbphp file

68
How to take a variable inside if else statement in PHP

How to take a variable inside if else statement in PHP

I am trying to take a value inside of if/else statement and send an error message with "that variable" because I don't want any of my inputs to be more than 99 characters

81