Welcome Guest, Not a member yet? Register   Sign In
Array to string conversion error when sorting array
#2

(This post was last modified: 11-17-2020, 10:49 PM by schertt.)

You're trying to sort the values of $test as if they are alphanumeric strings (this is what "natural ordering" is) but the aren't strings, they're Arrays. Take another look at it:


PHP Code:
$test = [
  0 => ['weight' => '90 kg'],
  1 => ['weight' => '92 kg'],
  2 => ['weight' => '100 kg'],
  3 => ['weight' => '94 kg'],
  4 => ['weight' => '98 kg'],
  5 => ['weight' => '125 kg']
]; 


Anything that attempts to sort this by natural order is going to fail because you can't convert an Array to a string. This is why your the last three commands fail. 

I also suspect that asort isn't actually working as you intended either. 

PHP Code:
php $test = [
php >  0 => ['weight' => '90 kg'],
php >  1 => ['weight' => '92 kg'],
php >  2 => ['weight' => '100 kg'],
php >  3 => ['weight' => '94 kg'],
php >  4 => ['weight' => '98 kg'],
php >  5 => ['weight' => '125 kg']
php > ];
php var_dump(asort($test));
php shell code:1:
bool(true)
php var_dump($test);
php shell code:1:
array(
6) {
  [2] =>
  array(1) {
    'weight' =>
    string(6"100 kg"
  }
  [5] =>
  array(1) {
    'weight' =>
    string(6"125 kg"
  }
  [0] =>
  array(1) {
    'weight' =>
    string(5"90 kg"
  }
  [1] =>
  array(1) {
    'weight' =>
    string(5"92 kg"
  }
  [3] =>
  array(1) {
    'weight' =>
    string(5"94 kg"
  }
  [4] =>
  array(1) {
    'weight' =>
    string(5"98 kg"
  }
}
php 

Here's a hint that might get you started in the right direction:

PHP Code:
php > foreach ($test as $k=>&$v){$v $v['weight'];}
php > unset($v); var_dump($test);
php shell code:1:
array(
6) {
  [0] =>
  string(5"90 kg"
  [1] =>
  string(5"92 kg"
  [2] =>
  string(6"100 kg"
  [3] =>
  string(5"94 kg"
  [4] =>
  string(5"98 kg"
  [5] =>
  string(6"125 kg"

Reply


Messages In This Thread
RE: Array to string conversion error when sorting array - by schertt - 11-17-2020, 10:42 PM



Theme © iAndrew 2016 - Forum software by © MyBB