0

I have an array in this format

$dataArray = "array (
  0 => 
  array (
    'Field Val' =>'val1',
    'Field Val2' =>'val2',
  ),
  1 => 
  array (
    'Field Val' =>'val1',
    'Field Val2' =>'val2'
  )";

I want to iterate this array and return it in the format below

foreach($dataArray as $data) {
  $newArray = ['name'=>val1,'address'=>val2];
}

How can I do this? Please help.

  • 1
    that's not an array, that's a string. and not even one that you convert easily. – Philipp Sander Feb 8 at 8:18
  • double quote also there or you just added? – Amit Naraniwal Feb 8 at 8:20
  • also "name" and "address" ca not be found in the given string – Philipp Sander Feb 8 at 8:23
  • 1
    this code is all over the place. it's not valid PHP. fix this first – Philipp Sander Feb 8 at 8:28
1

that's not an array, that's a string.

And another problem is, that it's not even valid json nor valid php code.

you have to fix this first.

But the much better solution is to figure out were that string comes from, because it obviously was an array before you probably called var_dump on it.

you probably want this:

$dataArray = array (
  0 => 
  array (
    'Field Val' =>'val1',
    'Field Val2' =>'val2',
  ),
  1 => 
  array (
    'Field Val' =>'val1',
    'Field Val2' =>'val2'
  )
);

valid php as string

you have to eval() to create the code in your string. and then you have an array.

If you would work with strings in json notation this would be the preffered way:

you can use $dataArray = json_decode($dataArray, true); to convert it to an actual array.

The much cleaner way is to inject \Magento\Framework\Serialize\Serializer\Json and use serialize($data)

0

You can try the array_merge in your example try this one :

function array_flatten($array) { 
  if (!is_array($array)) { 
    return FALSE; 
  } 
  $result = array(); 
  foreach ($array as $key => $value) { 
    if (is_array($value)) { 
      $result = array_merge($result, array_flatten($value)); 
    } 
    else { 
      $result[$key] = $value; 
    } 
  } 
  return $result; 
} 

$dataArray = array (
  0 => 
  array (
    'Field1' =>'val1',
    'Field2' =>'val2',
  ),
  1 => 
  array (
    'Field3' =>'val1',
    'Field4' =>'val2'
  ));

  echo"<pre/>";
  print_r(array_flatten($dataArray));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.