0

How to convert an array from a Postgres query to array variable in Laravel?

My postgres array structure

I have result var_dump from Laravel:

0 => array:1 [
    "order_itemset" => "{8,11}"
  ]
1 => array:1 [
"order_itemset" => "{8,12}"
  ]
2 => array:1 [
"order_itemset" => "{17,10}"
  ]
]

How can I get the data and store the data to array variable?

like this

$data = [['8', '11'], ['8', '12'], ['17', '10']];
2
  • did you try foreach ? Commented Jun 7, 2020 at 8:29
  • nope, im newb can you explain how to use foreach for my case ? please Commented Jun 7, 2020 at 8:32

3 Answers 3

1

Take a look here.

You can simplify this code if your postgres query returns an array "[8,11]" instead of a "sort-of" JSON "{8,11}"

<?php
$values = array_column($your_data, 'order_itemset');
$values = array_map(function ($v) {
    preg_match("/^\{(.+)\}$/", $v, $matches);
    if ($matches[1]) {
        return explode(',', $matches[1]);
    }
    return null;
}, $values);
print_r($values);
Sign up to request clarification or add additional context in comments.

Comments

0

you can use foreach

$original_array = $your_array;   //Your base array that you showed us on your Question
$base_array = array();

foreach($original_array as $original)
{
    $child_array = array();

    foreach($original->order_itemset as $a)
    {
        $child_array[] = $a;
    }
    $base_array[] = $child_array;
    unset($child_array);
}

die($base_array);

Comments

0

You can iterate the rows and convert the string values to valid JSON and then parse to get int-type values. Demo

var_export(
    array_map(
        fn($row) => json_decode(strtr($row['order_itemset'], '{}', '[]')),
        $array
    )
);

Or if you don't mind string-type values, you can trim the outer curly braces and call explode(). Demo

var_export(
    array_map(
        fn($row) => explode(',', trim($row['order_itemset'], '{}')),
        $array
    )
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.